| 1 |
/* |
| 2 |
* |
| 3 |
* @build make examples |
| 4 |
* @server bin/multi-acceptor-processes 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 |
#include "hproc.h" |
| 14 |
|
| 15 |
static char protocol = 't'; |
| 16 |
static const char* protocolname = "tcp"; |
| 17 |
static const char* host = "0.0.0.0"; |
| 18 |
static int port = 1234; |
| 19 |
static int process_num = 4; |
| 20 |
|
| 21 |
static void on_close(hio_t* io) { |
| 22 |
printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); |
| 23 |
} |
| 24 |
|
| 25 |
static void on_recv(hio_t* io, void* buf, int readbytes) { |
| 26 |
// echo |
| 27 |
hio_write(io, buf, readbytes); |
| 28 |
} |
| 29 |
|
| 30 |
static void on_accept(hio_t* io) { |
| 31 |
char localaddrstr[SOCKADDR_STRLEN] = {0}; |
| 32 |
char peeraddrstr[SOCKADDR_STRLEN] = {0}; |
| 33 |
printf("pid=%ld connfd=%d [%s] <= [%s]\n", |
| 34 |
(long)hv_getpid(), |
| 35 |
(int)hio_fd(io), |
| 36 |
SOCKADDR_STR(hio_localaddr(io), localaddrstr), |
| 37 |
SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); |
| 38 |
|
| 39 |
hio_setcb_close(io, on_close); |
| 40 |
hio_setcb_read(io, on_recv); |
| 41 |
hio_read(io); |
| 42 |
} |
| 43 |
|
| 44 |
static void loop_proc(void* userdata) { |
| 45 |
int sockfd = (int)(intptr_t)(userdata); |
| 46 |
hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE); |
| 47 |
hio_t* io = hio_get(loop, sockfd); |
| 48 |
if (protocol == 't') { |
| 49 |
hio_setcb_accept(io, on_accept); |
| 50 |
hio_accept(io); |
| 51 |
} |
| 52 |
else if (protocol == 'u') { |
| 53 |
hio_setcb_read(io, on_recv); |
| 54 |
hio_read(io); |
| 55 |
} |
| 56 |
hloop_run(loop); |
| 57 |
} |
| 58 |
|
| 59 |
int main(int argc, char** argv) { |
| 60 |
if (argc < 2) { |
| 61 |
printf("Usage: cmd 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 |
proc_ctx_t ctx; |
| 88 |
memset(&ctx, 0, sizeof(ctx)); |
| 89 |
ctx.proc = loop_proc; |
| 90 |
ctx.proc_userdata = (void*)(intptr_t)sockfd; |
| 91 |
for (int i = 0; i < process_num; ++i) { |
| 92 |
hproc_spawn(&ctx); |
| 93 |
} |
| 94 |
|
| 95 |
while(1) hv_sleep(1); |
| 96 |
|
| 97 |
return 0; |
| 98 |
} |