client.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "hloop.h"
  2. #define RECV_BUFSIZE 4096
  3. static char readbuf[RECV_BUFSIZE];
  4. void on_timer(htimer_t* timer) {
  5. static int cnt = 0;
  6. printf("on_timer timer_id=%lu time=%lus cnt=%d\n", timer->event_id, hloop_now(timer->loop), ++cnt);
  7. }
  8. void on_idle(hidle_t* idle) {
  9. static int cnt = 0;
  10. printf("on_idle idle_id=%lu cnt=%d\n", idle->event_id, ++cnt);
  11. }
  12. void on_write(hio_t* io, const void* buf, int writebytes) {
  13. printf("on_write fd=%d writebytes=%d\n", io->fd, writebytes);
  14. }
  15. void on_stdin(hio_t* io, void* buf, int readbytes) {
  16. printf("on_stdin fd=%d readbytes=%d\n", io->fd, readbytes);
  17. printf("> %s\n", buf);
  18. hio_t* iosock = (hio_t*)io->userdata;
  19. hwrite(iosock->loop, iosock->fd, buf, readbytes, on_write);
  20. }
  21. void on_read(hio_t* io, void* buf, int readbytes) {
  22. printf("on_read fd=%d readbytes=%d\n", io->fd, readbytes);
  23. printf("< %s\n", buf);
  24. printf(">>");
  25. fflush(stdout);
  26. }
  27. void on_close(hio_t* io) {
  28. printf("on_close fd=%d error=%d\n", io->fd, io->error);
  29. hio_t* iostdin = (hio_t*)io->userdata;
  30. hio_del(iostdin, READ_EVENT);
  31. }
  32. void on_connect(hio_t* io, int state) {
  33. printf("on_connect fd=%d state=%d\n", io->fd, state);
  34. if (state == 0) {
  35. printf("error=%d:%s\n", io->error, strerror(io->error));
  36. return;
  37. }
  38. struct sockaddr_in* localaddr = (struct sockaddr_in*)io->localaddr;
  39. struct sockaddr_in* peeraddr = (struct sockaddr_in*)io->peeraddr;
  40. printf("connect connfd=%d [%s:%d] => [%s:%d]\n", io->fd,
  41. inet_ntoa(localaddr->sin_addr), ntohs(localaddr->sin_port),
  42. inet_ntoa(peeraddr->sin_addr), ntohs(peeraddr->sin_port));
  43. // NOTE: just on loop, readbuf can be shared.
  44. hio_t* iostdin = hread(io->loop, 0, readbuf, RECV_BUFSIZE, on_stdin);
  45. iostdin->userdata = io;
  46. hio_t* iosock = hread(io->loop, io->fd, readbuf, RECV_BUFSIZE, on_read);
  47. iosock->close_cb = on_close;
  48. iosock->userdata = iostdin;
  49. printf(">>");
  50. fflush(stdout);
  51. }
  52. int main(int argc, char** argv) {
  53. if (argc < 3) {
  54. printf("Usage: cmd host port\n");
  55. return -10;
  56. }
  57. const char* host = argv[1];
  58. int port = atoi(argv[2]);
  59. hloop_t loop;
  60. hloop_init(&loop);
  61. //hidle_add(&loop, on_idle, INFINITE);
  62. //htimer_add(&loop, on_timer, 1000, INFINITE);
  63. hio_t* io = hconnect(&loop, host, port, on_connect);
  64. if (io == NULL) {
  65. return -20;
  66. }
  67. printf("connfd=%d\n", io->fd);
  68. hloop_run(&loop);
  69. return 0;
  70. }