-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket_tcp_nonblk_server.c
59 lines (49 loc) · 1.56 KB
/
socket_tcp_nonblk_server.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
59
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h> // for memset()
#include <sys/ioctl.h> // for FIONBIO
#define MAX_SIZE 50000
#define SIZE_RCV 32768
static char szBuf[MAX_SIZE];
int main(void) {
int ret;
int rcvdLen;
unsigned short port = 9880;
int srcSocket;
int destSocket;
struct sockaddr_in srcAddr;
struct sockaddr_in dstAddr;
int dstAddrSize = sizeof(dstAddr);
int val = 1; // for nonblocking comm
memset(&srcAddr, 0, sizeof(srcAddr));
srcAddr.sin_port = htons(port);
srcAddr.sin_family = AF_INET;
srcAddr.sin_addr.s_addr = htonl(INADDR_ANY);
srcSocket = socket(AF_INET, SOCK_STREAM, 0);
bind(srcSocket, (struct sockaddr *) &srcAddr, sizeof(srcAddr));
listen(srcSocket, 1);
printf("before accept\n");
destSocket = accept(srcSocket, (struct sockaddr *) &dstAddr, &dstAddrSize);
printf("after accept %s\n", inet_ntoa(dstAddr.sin_addr));
ioctl(destSocket, FIONBIO, &val); // for nonblocking comm
while(1) {
memset(szBuf, 0, sizeof(szBuf));
rcvdLen = recv(destSocket, szBuf, SIZE_RCV+1, 0);
if (rcvdLen == -1) { // waiting
printf(".");
usleep(100);
continue;
}
// if (rcvdLen == 0 || rcvdLen == -1) {
if (rcvdLen == 0) { // shutdown by peer
ret = close(destSocket);
break;
}
// printf("rx: [%d] %s\n", strlen(szBuf), szBuf);
// printf("rx: %d \n", strlen(szBuf));
}
}