TcpClient.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. enable_unpack = false;
  45. }
  46. virtual ~TcpClientTmpl() {
  47. }
  48. const EventLoopPtr& loop() {
  49. return loop_thread.loop();
  50. }
  51. //@retval >=0 connfd, <0 error
  52. int createsocket(int port, const char* host = "127.0.0.1") {
  53. memset(&peeraddr, 0, sizeof(peeraddr));
  54. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  55. if (ret != 0) {
  56. return -1;
  57. }
  58. return createsocket(&peeraddr.sa);
  59. }
  60. int createsocket(struct sockaddr* peeraddr) {
  61. int connfd = socket(peeraddr->sa_family, SOCK_STREAM, 0);
  62. // SOCKADDR_PRINT(peeraddr);
  63. if (connfd < 0) {
  64. perror("socket");
  65. return -2;
  66. }
  67. hio_t* io = hio_get(loop_thread.hloop(), connfd);
  68. assert(io != NULL);
  69. hio_set_peeraddr(io, peeraddr, SOCKADDR_LEN(peeraddr));
  70. channel.reset(new TSocketChannel(io));
  71. return connfd;
  72. }
  73. void closesocket() {
  74. if (channel) {
  75. channel->close();
  76. channel = NULL;
  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. void stop(bool wait_threads_stopped = true) {
  147. enable_reconnect = false;
  148. loop_thread.stop(wait_threads_stopped);
  149. }
  150. bool isConnected() {
  151. if (channel == NULL) return false;
  152. return channel->isConnected();
  153. }
  154. int send(const void* data, int size) {
  155. if (!isConnected()) return -1;
  156. return channel->write(data, size);
  157. }
  158. int send(Buffer* buf) {
  159. return send(buf->data(), buf->size());
  160. }
  161. int send(const std::string& str) {
  162. return send(str.data(), str.size());
  163. }
  164. int withTLS(const char* cert_file = NULL, const char* key_file = NULL, bool verify_peer = false) {
  165. if (cert_file) {
  166. hssl_ctx_init_param_t param;
  167. memset(&param, 0, sizeof(param));
  168. param.crt_file = cert_file;
  169. param.key_file = key_file;
  170. param.verify_peer = verify_peer ? 1 : 0;
  171. param.endpoint = HSSL_CLIENT;
  172. if (hssl_ctx_init(&param) == NULL) {
  173. fprintf(stderr, "hssl_ctx_init failed!\n");
  174. return -1;
  175. }
  176. }
  177. tls = true;
  178. return 0;
  179. }
  180. void setConnectTimeout(int ms) {
  181. connect_timeout = ms;
  182. }
  183. void setReconnect(ReconnectInfo* info) {
  184. if (info) {
  185. enable_reconnect = true;
  186. reconnect_info = *info;
  187. } else {
  188. enable_reconnect = false;
  189. }
  190. }
  191. void setUnpack(unpack_setting_t* setting) {
  192. if (setting) {
  193. enable_unpack = true;
  194. unpack_setting = *setting;
  195. } else {
  196. enable_unpack = false;
  197. }
  198. }
  199. public:
  200. TSocketChannelPtr channel;
  201. sockaddr_u peeraddr;
  202. bool tls;
  203. int connect_timeout;
  204. bool enable_reconnect;
  205. ReconnectInfo reconnect_info;
  206. bool enable_unpack;
  207. unpack_setting_t unpack_setting;
  208. // Callback
  209. std::function<void(const TSocketChannelPtr&)> onConnection;
  210. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  211. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  212. private:
  213. EventLoopThread loop_thread;
  214. };
  215. typedef TcpClientTmpl<SocketChannel> TcpClient;
  216. }
  217. #endif // HV_TCP_CLIENT_HPP_