1
0

server.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "hloop.h"
  2. #include "hsocket.h"
  3. #define RECV_BUFSIZE 4096
  4. static char readbuf[RECV_BUFSIZE];
  5. void on_timer(htimer_t* timer) {
  6. static int cnt = 0;
  7. printf("on_timer timer_id=%lu time=%lus cnt=%d\n", timer->event_id, hloop_now(timer->loop), ++cnt);
  8. }
  9. void on_idle(hidle_t* idle) {
  10. static int cnt = 0;
  11. printf("on_idle idle_id=%lu cnt=%d\n", idle->event_id, ++cnt);
  12. }
  13. void on_write(hio_t* io, const void* buf, int writebytes) {
  14. printf("on_write fd=%d writebytes=%d\n", io->fd, writebytes);
  15. }
  16. void on_close(hio_t* io) {
  17. printf("on_close fd=%d error=%d\n", io->fd, io->error);
  18. }
  19. void on_read(hio_t* io, void* buf, int readbytes) {
  20. printf("on_read fd=%d readbytes=%d\n", io->fd, readbytes);
  21. printf("< %s\n", buf);
  22. // echo
  23. printf("> %s\n", buf);
  24. hwrite(io->loop, io->fd, buf, readbytes, on_write);
  25. }
  26. void on_accept(hio_t* io, int connfd) {
  27. printf("on_accept listenfd=%d connfd=%d\n", io->fd, connfd);
  28. char localaddrstr[INET6_ADDRSTRLEN+16] = {0};
  29. char peeraddrstr[INET6_ADDRSTRLEN+16] = {0};
  30. printf("accept listenfd=%d connfd=%d [%s] <= [%s]\n", io->fd, connfd,
  31. sockaddr_snprintf(io->localaddr, localaddrstr, sizeof(localaddrstr)),
  32. sockaddr_snprintf(io->peeraddr, peeraddrstr, sizeof(peeraddrstr)));
  33. // one loop can use one readbuf
  34. hio_t* connio = hread(io->loop, connfd, readbuf, RECV_BUFSIZE, on_read);
  35. connio->close_cb = on_close;
  36. }
  37. int main(int argc, char** argv) {
  38. if (argc < 2) {
  39. printf("Usage: cmd port\n");
  40. return -10;
  41. }
  42. int port = atoi(argv[1]);
  43. hloop_t loop;
  44. hloop_init(&loop);
  45. //hidle_add(&loop, on_idle, INFINITE);
  46. //htimer_add(&loop, on_timer, 1000, INFINITE);
  47. hio_t* io = hlisten(&loop, port, on_accept);
  48. if (io == NULL) {
  49. return -20;
  50. }
  51. printf("listenfd=%d\n", io->fd);
  52. hloop_run(&loop);
  53. }