multi-acceptor-processes.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. #include "hloop.h"
  10. #include "hsocket.h"
  11. #include "hthread.h"
  12. #include "hproc.h"
  13. static char protocol = 't';
  14. static const char* protocolname = "tcp";
  15. static const char* host = "0.0.0.0";
  16. static int port = 1234;
  17. static int process_num = 4;
  18. static void on_close(hio_t* io) {
  19. printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
  20. }
  21. static void on_recv(hio_t* io, void* buf, int readbytes) {
  22. // echo
  23. hio_write(io, buf, readbytes);
  24. }
  25. static void on_accept(hio_t* io) {
  26. char localaddrstr[SOCKADDR_STRLEN] = {0};
  27. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  28. printf("pid=%ld connfd=%d [%s] <= [%s]\n",
  29. (long)hv_getpid(),
  30. (int)hio_fd(io),
  31. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  32. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  33. hio_setcb_close(io, on_close);
  34. hio_setcb_read(io, on_recv);
  35. hio_read(io);
  36. }
  37. static void loop_proc(void* userdata) {
  38. int sockfd = (int)(intptr_t)(userdata);
  39. hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
  40. hio_t* io = hio_get(loop, sockfd);
  41. if (protocol == 't') {
  42. hio_setcb_accept(io, on_accept);
  43. hio_accept(io);
  44. }
  45. else if (protocol == 'u') {
  46. hio_setcb_read(io, on_recv);
  47. hio_read(io);
  48. }
  49. hloop_run(loop);
  50. }
  51. int main(int argc, char** argv) {
  52. if (argc < 2) {
  53. printf("Usage: cmd port\n");
  54. return -10;
  55. }
  56. int index = 1;
  57. if (argv[1][0] == '-') {
  58. protocol = argv[1][1];
  59. switch(protocol) {
  60. case 't': protocolname = "tcp"; break;
  61. case 'u': protocolname = "udp"; break;
  62. default: fprintf(stderr, "Unsupported protocol '%c'\n", protocol); exit(1);
  63. }
  64. ++index;
  65. }
  66. port = atoi(argv[index++]);
  67. int sockfd = -1;
  68. if (protocol == 't') {
  69. sockfd = Listen(port, host);
  70. }
  71. else if (protocol == 'u') {
  72. sockfd = Bind(port, host, SOCK_DGRAM);
  73. }
  74. if (sockfd < 0) {
  75. exit(1);
  76. }
  77. proc_ctx_t ctx;
  78. memset(&ctx, 0, sizeof(ctx));
  79. ctx.proc = loop_proc;
  80. ctx.proc_userdata = (void*)(intptr_t)sockfd;
  81. for (int i = 0; i < process_num; ++i) {
  82. hproc_spawn(&ctx);
  83. }
  84. while(1) hv_sleep(1);
  85. return 0;
  86. }