client.cpp 2.5 KB

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