multi-acceptor-threads.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 const char* host = "0.0.0.0";
  13. static int port = 1234;
  14. static int thread_num = 4;
  15. static int listenfd = INVALID_SOCKET;
  16. static void on_close(hio_t* io) {
  17. printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
  18. }
  19. static void on_recv(hio_t* io, void* buf, int readbytes) {
  20. // echo
  21. hio_write(io, buf, readbytes);
  22. }
  23. static void on_accept(hio_t* io) {
  24. char localaddrstr[SOCKADDR_STRLEN] = {0};
  25. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  26. printf("tid=%ld connfd=%d [%s] <= [%s]\n",
  27. (long)hv_gettid(),
  28. (int)hio_fd(io),
  29. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  30. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  31. hio_setcb_close(io, on_close);
  32. hio_setcb_read(io, on_recv);
  33. hio_read(io);
  34. }
  35. static HTHREAD_ROUTINE(loop_thread) {
  36. hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
  37. haccept(loop, listenfd, on_accept);
  38. hloop_run(loop);
  39. return 0;
  40. }
  41. int main(int argc, char** argv) {
  42. if (argc < 2) {
  43. printf("Usage: cmd port\n");
  44. return -10;
  45. }
  46. port = atoi(argv[1]);
  47. listenfd = Listen(port, host);
  48. if (listenfd < 0) {
  49. exit(1);
  50. }
  51. for (int i = 0; i < thread_num; ++i) {
  52. hthread_create(loop_thread, NULL);
  53. }
  54. while(1) hv_sleep(1);
  55. return 0;
  56. }