TcpClient.h 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. template<class TSocketChannel = SocketChannel>
  37. class TcpClientTmpl {
  38. public:
  39. typedef std::shared_ptr<TSocketChannel> TSocketChannelPtr;
  40. TcpClientTmpl() {
  41. tls = false;
  42. connect_timeout = 5000;
  43. enable_reconnect = false;
  44. }
  45. virtual ~TcpClientTmpl() {
  46. }
  47. const EventLoopPtr& loop() {
  48. return loop_thread.loop();
  49. }
  50. //@retval >=0 connfd, <0 error
  51. int createsocket(int port, const char* host = "127.0.0.1") {
  52. memset(&peeraddr, 0, sizeof(peeraddr));
  53. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  54. if (ret != 0) {
  55. return -1;
  56. }
  57. return createsocket(&peeraddr.sa);
  58. }
  59. int createsocket(struct sockaddr* peeraddr) {
  60. int connfd = socket(peeraddr->sa_family, SOCK_STREAM, 0);
  61. // SOCKADDR_PRINT(peeraddr);
  62. if (connfd < 0) {
  63. perror("socket");
  64. return -2;
  65. }
  66. hio_t* io = hio_get(loop_thread.hloop(), connfd);
  67. assert(io != NULL);
  68. hio_set_peeraddr(io, peeraddr, SOCKADDR_LEN(peeraddr));
  69. channel.reset(new TSocketChannel(io));
  70. return connfd;
  71. }
  72. int startConnect() {
  73. assert(channel != NULL);
  74. if (tls) {
  75. channel->enableSSL();
  76. }
  77. if (connect_timeout) {
  78. channel->setConnectTimeout(connect_timeout);
  79. }
  80. channel->onconnect = [this]() {
  81. channel->startRead();
  82. if (onConnection) {
  83. onConnection(channel);
  84. }
  85. };
  86. channel->onread = [this](Buffer* buf) {
  87. if (onMessage) {
  88. onMessage(channel, buf);
  89. }
  90. };
  91. channel->onwrite = [this](Buffer* buf) {
  92. if (onWriteComplete) {
  93. onWriteComplete(channel, buf);
  94. }
  95. };
  96. channel->onclose = [this]() {
  97. if (onConnection) {
  98. onConnection(channel);
  99. }
  100. // reconnect
  101. if (enable_reconnect) {
  102. startReconnect();
  103. } else {
  104. channel = NULL;
  105. // NOTE: channel should be destroyed,
  106. // so in this lambda function, no code should be added below.
  107. }
  108. };
  109. return channel->startConnect();
  110. }
  111. int startReconnect() {
  112. if (++reconnect_info.cur_retry_cnt > reconnect_info.max_retry_cnt) return 0;
  113. if (reconnect_info.delay_policy == 0) {
  114. // fixed
  115. reconnect_info.cur_delay = reconnect_info.min_delay;
  116. } else if (reconnect_info.delay_policy == 1) {
  117. // linear
  118. reconnect_info.cur_delay += reconnect_info.min_delay;
  119. } else {
  120. // exponential
  121. reconnect_info.cur_delay *= reconnect_info.delay_policy;
  122. }
  123. reconnect_info.cur_delay = MAX(reconnect_info.cur_delay, reconnect_info.min_delay);
  124. reconnect_info.cur_delay = MIN(reconnect_info.cur_delay, reconnect_info.max_delay);
  125. loop_thread.loop()->setTimeout(reconnect_info.cur_delay, [this](TimerID timerID){
  126. hlogi("reconnect... cnt=%d, delay=%d", reconnect_info.cur_retry_cnt, reconnect_info.cur_delay);
  127. // printf("reconnect... cnt=%d, delay=%d\n", reconnect_info.cur_retry_cnt, reconnect_info.cur_delay);
  128. createsocket(&peeraddr.sa);
  129. startConnect();
  130. });
  131. return 0;
  132. }
  133. void start(bool wait_threads_started = true) {
  134. loop_thread.start(wait_threads_started, std::bind(&TcpClientTmpl::startConnect, this));
  135. }
  136. void stop(bool wait_threads_stopped = true) {
  137. enable_reconnect = false;
  138. loop_thread.stop(wait_threads_stopped);
  139. }
  140. int withTLS(const char* cert_file = NULL, const char* key_file = NULL) {
  141. tls = true;
  142. if (cert_file) {
  143. hssl_ctx_init_param_t param;
  144. memset(&param, 0, sizeof(param));
  145. param.crt_file = cert_file;
  146. param.key_file = key_file;
  147. param.endpoint = 1;
  148. return hssl_ctx_init(&param) == NULL ? -1 : 0;
  149. }
  150. return 0;
  151. }
  152. void setConnectTimeout(int ms) {
  153. connect_timeout = ms;
  154. }
  155. void setReconnect(ReconnectInfo* info) {
  156. enable_reconnect = true;
  157. reconnect_info = *info;
  158. }
  159. public:
  160. TSocketChannelPtr channel;
  161. sockaddr_u peeraddr;
  162. bool tls;
  163. int connect_timeout;
  164. bool enable_reconnect;
  165. ReconnectInfo reconnect_info;
  166. // Callback
  167. std::function<void(const TSocketChannelPtr&)> onConnection;
  168. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  169. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  170. private:
  171. EventLoopThread loop_thread;
  172. };
  173. typedef TcpClientTmpl<SocketChannel> TcpClient;
  174. }
  175. #endif // HV_TCP_CLIENT_HPP_