TcpClient.h 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #ifndef HV_TCP_CLIENT_HPP_
  2. #define HV_TCP_CLIENT_HPP_
  3. #include "hsocket.h"
  4. #include "hssl.h"
  5. #include "hlog.h"
  6. #include "EventLoopThread.h"
  7. #include "Callback.h"
  8. #include "Channel.h"
  9. namespace hv {
  10. struct ReconnectInfo {
  11. uint32_t min_delay; // ms
  12. uint32_t max_delay; // ms
  13. uint32_t cur_delay; // ms
  14. /*
  15. * @delay_policy
  16. * 0: fixed
  17. * min_delay=3s => 3,3,3...
  18. * 1: linear
  19. * min_delay=3s max_delay=10s => 3,6,9,10,10...
  20. * other: exponential
  21. * min_delay=3s max_delay=60s delay_policy=2 => 3,6,12,24,48,60,60...
  22. */
  23. uint32_t delay_policy;
  24. uint32_t max_retry_cnt;
  25. uint32_t cur_retry_cnt;
  26. ReconnectInfo() {
  27. min_delay = 1000;
  28. max_delay = 60000;
  29. cur_delay = 0;
  30. // 1,2,4,8,16,32,60,60...
  31. delay_policy = 2;
  32. max_retry_cnt = INFINITE;
  33. cur_retry_cnt = 0;
  34. }
  35. };
  36. class TcpClient {
  37. public:
  38. TcpClient() {
  39. tls = false;
  40. connect_timeout = 5000;
  41. enable_reconnect = false;
  42. }
  43. ~TcpClient() {
  44. }
  45. EventLoopPtr loop() {
  46. return loop_thread.loop();
  47. }
  48. //@retval >=0 connfd, <0 error
  49. int createsocket(int port, const char* host = "127.0.0.1") {
  50. memset(&peeraddr, 0, sizeof(peeraddr));
  51. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  52. if (ret != 0) {
  53. return -1;
  54. }
  55. return createsocket(&peeraddr.sa);
  56. }
  57. int createsocket(struct sockaddr* peeraddr) {
  58. int connfd = socket(peeraddr->sa_family, SOCK_STREAM, 0);
  59. // SOCKADDR_PRINT(peeraddr);
  60. if (connfd < 0) {
  61. perror("socket");
  62. return -2;
  63. }
  64. hio_t* io = hio_get(loop_thread.hloop(), connfd);
  65. assert(io != NULL);
  66. hio_set_peeraddr(io, peeraddr, SOCKADDR_LEN(peeraddr));
  67. channel.reset(new SocketChannel(io));
  68. return connfd;
  69. }
  70. int startConnect() {
  71. assert(channel != NULL);
  72. if (tls) {
  73. channel->enableSSL();
  74. }
  75. if (connect_timeout) {
  76. channel->setConnectTimeout(connect_timeout);
  77. }
  78. channel->onconnect = [this]() {
  79. channel->startRead();
  80. if (onConnection) {
  81. onConnection(channel);
  82. }
  83. };
  84. channel->onread = [this](Buffer* buf) {
  85. if (onMessage) {
  86. onMessage(channel, buf);
  87. }
  88. };
  89. channel->onwrite = [this](Buffer* buf) {
  90. if (onWriteComplete) {
  91. onWriteComplete(channel, buf);
  92. }
  93. };
  94. channel->onclose = [this]() {
  95. if (onConnection) {
  96. onConnection(channel);
  97. }
  98. channel = NULL;
  99. // reconnect
  100. if (enable_reconnect) {
  101. startReconnect();
  102. }
  103. };
  104. return channel->startConnect();
  105. }
  106. int startReconnect() {
  107. if (++reconnect_info.cur_retry_cnt > reconnect_info.max_retry_cnt) return 0;
  108. if (reconnect_info.delay_policy == 0) {
  109. // fixed
  110. reconnect_info.cur_delay = reconnect_info.min_delay;
  111. } else if (reconnect_info.delay_policy == 1) {
  112. // linear
  113. reconnect_info.cur_delay += reconnect_info.min_delay;
  114. } else {
  115. // exponential
  116. reconnect_info.cur_delay *= reconnect_info.delay_policy;
  117. }
  118. reconnect_info.cur_delay = MAX(reconnect_info.cur_delay, reconnect_info.min_delay);
  119. reconnect_info.cur_delay = MIN(reconnect_info.cur_delay, reconnect_info.max_delay);
  120. loop_thread.loop()->setTimeout(reconnect_info.cur_delay, [this](TimerID timerID){
  121. hlogi("reconnect... cnt=%d, delay=%d", reconnect_info.cur_retry_cnt, reconnect_info.cur_delay);
  122. // printf("reconnect... cnt=%d, delay=%d\n", reconnect_info.cur_retry_cnt, reconnect_info.cur_delay);
  123. createsocket(&peeraddr.sa);
  124. startConnect();
  125. });
  126. return 0;
  127. }
  128. void start(bool wait_threads_started = true) {
  129. loop_thread.start(wait_threads_started, std::bind(&TcpClient::startConnect, this));
  130. }
  131. void stop(bool wait_threads_stopped = true) {
  132. loop_thread.stop(wait_threads_stopped);
  133. }
  134. int withTLS(const char* cert_file = NULL, const char* key_file = NULL) {
  135. tls = true;
  136. hssl_ctx_init_param_t param;
  137. memset(&param, 0, sizeof(param));
  138. param.crt_file = cert_file;
  139. param.key_file = key_file;
  140. return hssl_ctx_init(&param) == NULL ? -1 : 0;
  141. }
  142. void setConnectTimeout(int ms) {
  143. connect_timeout = ms;
  144. }
  145. void setReconnect(ReconnectInfo* info) {
  146. enable_reconnect = true;
  147. reconnect_info = *info;
  148. }
  149. public:
  150. SocketChannelPtr channel;
  151. sockaddr_u peeraddr;
  152. bool tls;
  153. int connect_timeout;
  154. bool enable_reconnect;
  155. ReconnectInfo reconnect_info;
  156. // Callback
  157. ConnectionCallback onConnection;
  158. MessageCallback onMessage;
  159. WriteCompleteCallback onWriteComplete;
  160. private:
  161. EventLoopThread loop_thread;
  162. };
  163. }
  164. #endif // HV_TCP_CLIENT_HPP_