-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08.practical.work.server.nonblock.c
59 lines (57 loc) · 1.62 KB
/
08.practical.work.server.nonblock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int sockfd, clientfd;
socklen_t clen;
ssize_t messageSize;
struct sockaddr_in saddr, caddr;
char message[256];
unsigned short port = 8782;
//create socket()
if ((sockfd=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("Error creating socket\n");
}
//setsockopt() - reuse address/
setsockopt(sockfd, SOL_SOCKET,
SO_REUSEADDR, &(int){ 1 },
sizeof(int));
//fcntl() - nonblocking
int fl = fcntl(sockfd, F_GETFL, 0);
fl |= O_NONBLOCK;
fcntl(sockfd, F_SETFL, fl);
//bind()
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
saddr.sin_port = htons(port);
if ((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0)) {
printf("Error binding\n");
}
//listen()
if (listen(sockfd, 5) < 0) {
printf("Error listening\n");
}
while(1){
clen=sizeof(caddr);
if ((clientfd=accept(sockfd, (struct sockaddr *) &caddr, &clen)) > 0) {
int fl = fcntl(clientfd, F_GETFL, 0);
fl |= O_NONBLOCK;
fcntl(clientfd, F_SETFL, fl);
while (1) {
//Receive message
messageSize = recv(clientfd, message, sizeof(message), 0);
if (messageSize > 0){
printf("@@@@@@@@@@@@ Client: %s\n",message);
}
}
}
}
return 0;
}