Debian Codegraph @

third-party/libhv-v1.3.3/examples/multi-thread/multi-acceptor-threads.c

raw
1 /*
2 *
3 * @build make examples
4 * @server bin/multi-acceptor-threads 1234
5 * @client bin/nc 127.0.0.1 1234
6 * nc 127.0.0.1 1234
7 * telnet 127.0.0.1 1234
8 */
9
10 #include "hloop.h"
11 #include "hsocket.h"
12 #include "hthread.h"
13
14 static char protocol = 't';
15 static const char* protocolname = "tcp";
16 static const char* host = "0.0.0.0";
17 static int port = 1234;
18 static int thread_num = 4;
19
20 static void on_close(hio_t* io) {
21 printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
22 }
23
24 static void on_recv(hio_t* io, void* buf, int readbytes) {
25 // echo
26 hio_write(io, buf, readbytes);
27 }
28
29 static void on_accept(hio_t* io) {
30 char localaddrstr[SOCKADDR_STRLEN] = {0};
31 char peeraddrstr[SOCKADDR_STRLEN] = {0};
32 printf("tid=%ld connfd=%d [%s] <= [%s]\n",
33 (long)hv_gettid(),
34 (int)hio_fd(io),
35 SOCKADDR_STR(hio_localaddr(io), localaddrstr),
36 SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
37
38 hio_setcb_close(io, on_close);
39 hio_setcb_read(io, on_recv);
40 hio_read(io);
41 }
42
43 static HTHREAD_ROUTINE(loop_thread) {
44 int sockfd = (int)(intptr_t)(userdata);
45 hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
46 hio_t* io = hio_get(loop, sockfd);
47 if (protocol == 't') {
48 hio_setcb_accept(io, on_accept);
49 hio_accept(io);
50 }
51 else if (protocol == 'u') {
52 hio_setcb_read(io, on_recv);
53 hio_read(io);
54 }
55 hloop_run(loop);
56 return 0;
57 }
58
59 int main(int argc, char** argv) {
60 if (argc < 2) {
61 printf("Usage: cmd [-tu] port\n");
62 return -10;
63 }
64 int index = 1;
65 if (argv[1][0] == '-') {
66 protocol = argv[1][1];
67 switch(protocol) {
68 case 't': protocolname = "tcp"; break;
69 case 'u': protocolname = "udp"; break;
70 default: fprintf(stderr, "Unsupported protocol '%c'\n", protocol); exit(1);
71 }
72 ++index;
73 }
74 port = atoi(argv[index++]);
75
76 int sockfd = -1;
77 if (protocol == 't') {
78 sockfd = Listen(port, host);
79 }
80 else if (protocol == 'u') {
81 sockfd = Bind(port, host, SOCK_DGRAM);
82 }
83 if (sockfd < 0) {
84 exit(1);
85 }
86
87 for (int i = 0; i < thread_num; ++i) {
88 hthread_create(loop_thread, (void*)(intptr_t)sockfd);
89 }
90
91 while(1) hv_sleep(1);
92
93 return 0;
94 }