1
0

TcpClientEventLoop_test.cpp 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * TcpClientEventLoop_test.cpp
  3. *
  4. * @build make evpp
  5. * @server bin/TcpServer_test 1234
  6. * @client bin/TcpClientEventLoop_test 1234
  7. *
  8. */
  9. #include "TcpClient.h"
  10. #include "htime.h"
  11. #define TEST_RECONNECT 1
  12. #define TEST_TLS 0
  13. using namespace hv;
  14. class MyTcpClient : public TcpClient {
  15. public:
  16. MyTcpClient(EventLoopPtr loop = NULL) : TcpClient(loop) {
  17. onConnection = [this](const SocketChannelPtr& channel) {
  18. std::string peeraddr = channel->peeraddr();
  19. if (channel->isConnected()) {
  20. printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
  21. // send(time) every 3s
  22. setInterval(3000, [channel](TimerID timerID){
  23. if (channel->isConnected()) {
  24. if (channel->isWriteComplete()) {
  25. char str[DATETIME_FMT_BUFLEN] = {0};
  26. datetime_t dt = datetime_now();
  27. datetime_fmt(&dt, str);
  28. channel->write(str);
  29. }
  30. } else {
  31. killTimer(timerID);
  32. }
  33. });
  34. } else {
  35. printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
  36. }
  37. if (isReconnect()) {
  38. printf("reconnect cnt=%d, delay=%d\n", reconn_setting->cur_retry_cnt, reconn_setting->cur_delay);
  39. }
  40. };
  41. onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  42. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  43. };
  44. }
  45. int connect(int port) {
  46. int connfd = createsocket(port);
  47. if (connfd < 0) {
  48. return connfd;
  49. }
  50. #if TEST_RECONNECT
  51. // reconnect: 1,2,4,8,10,10,10...
  52. reconn_setting_t reconn;
  53. reconn_setting_init(&reconn);
  54. reconn.min_delay = 1000;
  55. reconn.max_delay = 10000;
  56. reconn.delay_policy = 2;
  57. setReconnect(&reconn);
  58. #endif
  59. #if TEST_TLS
  60. withTLS();
  61. #endif
  62. printf("client connect to port %d, connfd=%d ...\n", port, connfd);
  63. start();
  64. return connfd;
  65. }
  66. };
  67. typedef std::shared_ptr<MyTcpClient> MyTcpClientPtr;
  68. int main(int argc, char* argv[]) {
  69. if (argc < 2) {
  70. printf("Usage: %s port\n", argv[0]);
  71. return -10;
  72. }
  73. int port = atoi(argv[1]);
  74. EventLoopThreadPtr loop_thread(new EventLoopThread);
  75. loop_thread->start();
  76. MyTcpClientPtr cli1(new MyTcpClient(loop_thread->loop()));
  77. cli1->connect(port);
  78. MyTcpClientPtr cli2(new MyTcpClient(loop_thread->loop()));
  79. cli2->connect(port);
  80. // press Enter to stop
  81. while (getchar() != '\n');
  82. loop_thread->stop();
  83. loop_thread->join();
  84. return 0;
  85. }