-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_non_block_apply1_server.cpp
79 lines (60 loc) · 1.39 KB
/
tcp_non_block_apply1_server.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <cstdio>
#include <ctime>
#include <winsock.h>
int main() {
SOCKET sd, clnt_sd;
WSADATA wsadata;
struct sockaddr_in serv{}, clnt{};
int i, n;
char str[100];
clock_t t1, t2;
bool exit = false;
int status = 0;
WSAStartup(0x101, &wsadata);
sd = socket(AF_INET, SOCK_STREAM, 0);
serv.sin_family = AF_INET;
serv.sin_port = htons(1234);
serv.sin_addr.s_addr = inet_addr("127.0.0.1");
status = bind(sd, (struct sockaddr *) &serv, sizeof(serv));
printf("bind status: %d\n", status);
status = listen(sd, 5);
printf("listen status: %d\n", status);
int clnt_len = sizeof(clnt);
printf("Server waits.\n");
//while (true) {
clnt_sd = accept(sd, (struct sockaddr *) &clnt, &clnt_len);
printf("Client is connected.\n");
//enable non-blocking mode when iMode=1
u_long iMode = 1;
ioctlsocket(clnt_sd, FIONBIO, &iMode);
t2 = 0;
long time;
while (true) {
n = recv(clnt_sd, str, 100, 0);
if (n > 0) {
str[n] = '\0';
printf("(client): %s\n", str);
}
t1 = clock();
time = (t1 - t2) / CLOCKS_PER_SEC;
//printf("time: %ld\n", time);
if (time > 5) {
strcpy(str, "I know.");
printf("(server): %s\n", str);
send(clnt_sd, str, strlen(str) + 1, 0);
t2 = clock();
Sleep(800);
}
if (strcmp(str, "exit") == 0) {
exit = true;
break;
}
}
/*if (exit) {
break;
}
}*/
closesocket(sd);
closesocket(clnt_sd);
WSACleanup();
}