TcpClientEventLoop_test.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 TcpClientEventLoopTmpl<SocketChannel> {
  15. public:
  16. MyTcpClient(EventLoopPtr loop = NULL) : TcpClientEventLoopTmpl<SocketChannel>(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. return startConnect();
  64. }
  65. };
  66. typedef std::shared_ptr<MyTcpClient> MyTcpClientPtr;
  67. int main(int argc, char* argv[]) {
  68. if (argc < 2) {
  69. printf("Usage: %s port\n", argv[0]);
  70. return -10;
  71. }
  72. int port = atoi(argv[1]);
  73. EventLoopPtr loop(new EventLoop);
  74. MyTcpClientPtr cli1(new MyTcpClient(loop));
  75. cli1->connect(port);
  76. MyTcpClientPtr cli2(new MyTcpClient(loop));
  77. cli2->connect(port);
  78. loop->run();
  79. return 0;
  80. }