TcpClient.h 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 "Channel.h"
  8. namespace hv {
  9. struct ReconnectInfo {
  10. uint32_t min_delay; // ms
  11. uint32_t max_delay; // ms
  12. uint32_t cur_delay; // ms
  13. /*
  14. * @delay_policy
  15. * 0: fixed
  16. * min_delay=3s => 3,3,3...
  17. * 1: linear
  18. * min_delay=3s max_delay=10s => 3,6,9,10,10...
  19. * other: exponential
  20. * min_delay=3s max_delay=60s delay_policy=2 => 3,6,12,24,48,60,60...
  21. */
  22. uint32_t delay_policy;
  23. uint32_t max_retry_cnt;
  24. uint32_t cur_retry_cnt;
  25. ReconnectInfo() {
  26. min_delay = 1000;
  27. max_delay = 60000;
  28. cur_delay = 0;
  29. // 1,2,4,8,16,32,60,60...
  30. delay_policy = 2;
  31. max_retry_cnt = INFINITE;
  32. cur_retry_cnt = 0;
  33. }
  34. };
  35. template<class TSocketChannel = SocketChannel>
  36. class TcpClientTmpl {
  37. public:
  38. typedef std::shared_ptr<TSocketChannel> TSocketChannelPtr;
  39. TcpClientTmpl() {
  40. tls = false;
  41. connect_timeout = 5000;
  42. enable_reconnect = false;
  43. enable_unpack = 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. // closesocket thread-safe
  73. void closesocket() {
  74. enable_reconnect = false;
  75. if (channel) {
  76. channel->close(true);
  77. }
  78. }
  79. int startConnect() {
  80. assert(channel != NULL);
  81. if (tls) {
  82. channel->enableSSL();
  83. }
  84. if (connect_timeout) {
  85. channel->setConnectTimeout(connect_timeout);
  86. }
  87. channel->onconnect = [this]() {
  88. if (enable_unpack) {
  89. channel->setUnpack(&unpack_setting);
  90. }
  91. channel->startRead();
  92. if (onConnection) {
  93. onConnection(channel);
  94. }
  95. };
  96. channel->onread = [this](Buffer* buf) {
  97. if (onMessage) {
  98. onMessage(channel, buf);
  99. }
  100. };
  101. channel->onwrite = [this](Buffer* buf) {
  102. if (onWriteComplete) {
  103. onWriteComplete(channel, buf);
  104. }
  105. };
  106. channel->onclose = [this]() {
  107. if (onConnection) {
  108. onConnection(channel);
  109. }
  110. // reconnect
  111. if (enable_reconnect) {
  112. startReconnect();
  113. } else {
  114. channel = NULL;
  115. // NOTE: channel should be destroyed,
  116. // so in this lambda function, no code should be added below.
  117. }
  118. };
  119. return channel->startConnect();
  120. }
  121. int startReconnect() {
  122. if (++reconnect_info.cur_retry_cnt > reconnect_info.max_retry_cnt) return 0;
  123. if (reconnect_info.delay_policy == 0) {
  124. // fixed
  125. reconnect_info.cur_delay = reconnect_info.min_delay;
  126. } else if (reconnect_info.delay_policy == 1) {
  127. // linear
  128. reconnect_info.cur_delay += reconnect_info.min_delay;
  129. } else {
  130. // exponential
  131. reconnect_info.cur_delay *= reconnect_info.delay_policy;
  132. }
  133. reconnect_info.cur_delay = MAX(reconnect_info.cur_delay, reconnect_info.min_delay);
  134. reconnect_info.cur_delay = MIN(reconnect_info.cur_delay, reconnect_info.max_delay);
  135. loop_thread.loop()->setTimeout(reconnect_info.cur_delay, [this](TimerID timerID){
  136. hlogi("reconnect... cnt=%d, delay=%d", reconnect_info.cur_retry_cnt, reconnect_info.cur_delay);
  137. // printf("reconnect... cnt=%d, delay=%d\n", reconnect_info.cur_retry_cnt, reconnect_info.cur_delay);
  138. createsocket(&peeraddr.sa);
  139. startConnect();
  140. });
  141. return 0;
  142. }
  143. void start(bool wait_threads_started = true) {
  144. loop_thread.start(wait_threads_started, std::bind(&TcpClientTmpl::startConnect, this));
  145. }
  146. // stop thread-safe
  147. void stop(bool wait_threads_stopped = true) {
  148. enable_reconnect = false;
  149. loop_thread.stop(wait_threads_stopped);
  150. }
  151. bool isConnected() {
  152. if (channel == NULL) return false;
  153. return channel->isConnected();
  154. }
  155. // send thread-safe
  156. int send(const void* data, int size) {
  157. if (!isConnected()) return -1;
  158. return channel->write(data, size);
  159. }
  160. int send(Buffer* buf) {
  161. return send(buf->data(), buf->size());
  162. }
  163. int send(const std::string& str) {
  164. return send(str.data(), str.size());
  165. }
  166. // deprecated: use withTLS(opt) after createsocket
  167. int withTLS(const char* cert_file = NULL, const char* key_file = NULL, bool verify_peer = false) {
  168. if (cert_file) {
  169. hssl_ctx_init_param_t param;
  170. memset(&param, 0, sizeof(param));
  171. param.crt_file = cert_file;
  172. param.key_file = key_file;
  173. param.verify_peer = verify_peer ? 1 : 0;
  174. param.endpoint = HSSL_CLIENT;
  175. if (hssl_ctx_init(&param) == NULL) {
  176. fprintf(stderr, "hssl_ctx_init failed!\n");
  177. return -1;
  178. }
  179. }
  180. tls = true;
  181. return 0;
  182. }
  183. int withTLS(hssl_ctx_opt_t* opt) {
  184. if (!channel) return -1;
  185. return channel->newSslCtx(opt);
  186. }
  187. void setConnectTimeout(int ms) {
  188. connect_timeout = ms;
  189. }
  190. void setReconnect(ReconnectInfo* info) {
  191. if (info) {
  192. enable_reconnect = true;
  193. reconnect_info = *info;
  194. } else {
  195. enable_reconnect = false;
  196. }
  197. }
  198. void setUnpack(unpack_setting_t* setting) {
  199. if (setting) {
  200. enable_unpack = true;
  201. unpack_setting = *setting;
  202. } else {
  203. enable_unpack = false;
  204. }
  205. }
  206. public:
  207. TSocketChannelPtr channel;
  208. sockaddr_u peeraddr;
  209. bool tls;
  210. int connect_timeout;
  211. bool enable_reconnect;
  212. ReconnectInfo reconnect_info;
  213. bool enable_unpack;
  214. unpack_setting_t unpack_setting;
  215. // Callback
  216. std::function<void(const TSocketChannelPtr&)> onConnection;
  217. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  218. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  219. private:
  220. EventLoopThread loop_thread;
  221. };
  222. typedef TcpClientTmpl<SocketChannel> TcpClient;
  223. }
  224. #endif // HV_TCP_CLIENT_HPP_