-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse_select.cpp
More file actions
81 lines (66 loc) · 1.82 KB
/
Copy pathuse_select.cpp
File metadata and controls
81 lines (66 loc) · 1.82 KB
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
80
81
//
// Created by s on 19-5-4.
//
/*
* use_select
*/
#include "myutili.h"
int main (int argc, char *argv[])
{
if (argc <= 2)
{
printf ("usage: %s ip_address port_number\n", basename (argv[0]));
exit (EXIT_FAILURE);
}
const char *ip = argv[1];
int port = atoi (argv[2]);
int listenfd = Start_TCPserver_up (ip, port);
struct sockaddr_in cli_addr;
socklen_t cli_addr_length = sizeof (cli_addr);
int connfd = Accept (listenfd, (struct sockaddr *) &cli_addr, &cli_addr_length);
char remote_addr[INET_ADDRSTRLEN];
printf ("connected with ip: %s and port: %d\n",
inet_ntop (AF_INET, &cli_addr.sin_addr, remote_addr, INET_ADDRSTRLEN), ntohs (cli_addr.sin_port));
char buf[1024];
fd_set read_fds;
fd_set exception_fds;
FD_ZERO(&read_fds);
FD_ZERO(&exception_fds);
int nReuseAddr = 1;
setsockopt (connfd, SOL_SOCKET, SO_OOBINLINE, &nReuseAddr, sizeof (nReuseAddr));
int ret = 0;
while (1)
{
memset (buf, '\0', sizeof (buf));
FD_SET(connfd, &read_fds);
FD_SET(connfd, &exception_fds);
ret = select (connfd + 1, &read_fds, NULL, &exception_fds, NULL);
printf ("select one\n");
if (ret < 0)
{
printf ("selection failure\n");
break;
}
if (FD_ISSET(connfd, &read_fds))
{
ret = recv (connfd, buf, sizeof (buf) - 1, 0);
if (ret <= 0)
{
break;
}
printf ("get %d bytes of normal data: %s\n", ret, buf);
}
else if (FD_ISSET(connfd, &exception_fds))
{
ret = recv (connfd, buf, sizeof (buf) - 1, MSG_OOB);
if (ret <= 0)
{
break;
}
printf ("get %d bytes of oob data: %s\n", ret, buf);
}
}
close (connfd);
close (listenfd);
return 0;
}