multi-acceptor-threads.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. #include "hloop.h"
  10. #include "hsocket.h"
  11. #include "hthread.h"
  12. static char protocol = 't';
  13. static const char* protocolname = "tcp";
  14. static const char* host = "0.0.0.0";
  15. static int port = 1234;
  16. static int thread_num = 4;
  17. static void on_close(hio_t* io) {
  18. printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
  19. }
  20. static void on_recv(hio_t* io, void* buf, int readbytes) {
  21. // echo
  22. hio_write(io, buf, readbytes);
  23. }
  24. static void on_accept(hio_t* io) {
  25. char localaddrstr[SOCKADDR_STRLEN] = {0};
  26. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  27. printf("tid=%ld connfd=%d [%s] <= [%s]\n",
  28. (long)hv_gettid(),
  29. (int)hio_fd(io),
  30. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  31. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  32. hio_setcb_close(io, on_close);
  33. hio_setcb_read(io, on_recv);
  34. hio_read(io);
  35. }
  36. static HTHREAD_ROUTINE(loop_thread) {
  37. int sockfd = (int)(intptr_t)(userdata);
  38. hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
  39. hio_t* io = hio_get(loop, sockfd);
  40. if (protocol == 't') {
  41. hio_setcb_accept(io, on_accept);
  42. hio_accept(io);
  43. }
  44. else if (protocol == 'u') {
  45. hio_setcb_read(io, on_recv);
  46. hio_read(io);
  47. }
  48. hloop_run(loop);
  49. return 0;
  50. }
  51. int main(int argc, char** argv) {
  52. if (argc < 2) {
  53. printf("Usage: cmd [-tu] 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. for (int i = 0; i < thread_num; ++i) {
  78. hthread_create(loop_thread, (void*)(intptr_t)sockfd);
  79. }
  80. while(1) hv_sleep(1);
  81. return 0;
  82. }