TcpClient.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. void closesocket() {
  73. if (channel) {
  74. channel->close();
  75. channel = NULL;
  76. }
  77. }
  78. int startConnect() {
  79. assert(channel != NULL);
  80. if (tls) {
  81. channel->enableSSL();
  82. }
  83. if (connect_timeout) {
  84. channel->setConnectTimeout(connect_timeout);
  85. }
  86. channel->onconnect = [this]() {
  87. if (enable_unpack) {
  88. channel->setUnpack(&unpack_setting);
  89. }
  90. channel->startRead();
  91. if (onConnection) {
  92. onConnection(channel);
  93. }
  94. };
  95. channel->onread = [this](Buffer* buf) {
  96. if (onMessage) {
  97. onMessage(channel, buf);
  98. }
  99. };
  100. channel->onwrite = [this](Buffer* buf) {
  101. if (onWriteComplete) {
  102. onWriteComplete(channel, buf);
  103. }
  104. };
  105. channel->onclose = [this]() {
  106. if (onConnection) {
  107. onConnection(channel);
  108. }
  109. // reconnect
  110. if (enable_reconnect) {
  111. startReconnect();
  112. } else {
  113. channel = NULL;
  114. // NOTE: channel should be destroyed,
  115. // so in this lambda function, no code should be added below.
  116. }
  117. };
  118. return channel->startConnect();
  119. }
  120. int startReconnect() {
  121. if (++reconnect_info.cur_retry_cnt > reconnect_info.max_retry_cnt) return 0;
  122. if (reconnect_info.delay_policy == 0) {
  123. // fixed
  124. reconnect_info.cur_delay = reconnect_info.min_delay;
  125. } else if (reconnect_info.delay_policy == 1) {
  126. // linear
  127. reconnect_info.cur_delay += reconnect_info.min_delay;
  128. } else {
  129. // exponential
  130. reconnect_info.cur_delay *= reconnect_info.delay_policy;
  131. }
  132. reconnect_info.cur_delay = MAX(reconnect_info.cur_delay, reconnect_info.min_delay);
  133. reconnect_info.cur_delay = MIN(reconnect_info.cur_delay, reconnect_info.max_delay);
  134. loop_thread.loop()->setTimeout(reconnect_info.cur_delay, [this](TimerID timerID){
  135. hlogi("reconnect... cnt=%d, delay=%d", reconnect_info.cur_retry_cnt, reconnect_info.cur_delay);
  136. // printf("reconnect... cnt=%d, delay=%d\n", reconnect_info.cur_retry_cnt, reconnect_info.cur_delay);
  137. createsocket(&peeraddr.sa);
  138. startConnect();
  139. });
  140. return 0;
  141. }
  142. void start(bool wait_threads_started = true) {
  143. loop_thread.start(wait_threads_started, std::bind(&TcpClientTmpl::startConnect, this));
  144. }
  145. void stop(bool wait_threads_stopped = true) {
  146. enable_reconnect = false;
  147. loop_thread.stop(wait_threads_stopped);
  148. }
  149. bool isConnected() {
  150. if (channel == NULL) return false;
  151. return channel->isConnected();
  152. }
  153. int send(const void* data, int size) {
  154. if (!isConnected()) return -1;
  155. return channel->write(data, size);
  156. }
  157. int send(Buffer* buf) {
  158. return send(buf->data(), buf->size());
  159. }
  160. int send(const std::string& str) {
  161. return send(str.data(), str.size());
  162. }
  163. int withTLS(const char* cert_file = NULL, const char* key_file = NULL, bool verify_peer = false) {
  164. if (cert_file) {
  165. hssl_ctx_init_param_t param;
  166. memset(&param, 0, sizeof(param));
  167. param.crt_file = cert_file;
  168. param.key_file = key_file;
  169. param.verify_peer = verify_peer ? 1 : 0;
  170. param.endpoint = HSSL_CLIENT;
  171. if (hssl_ctx_init(&param) == NULL) {
  172. fprintf(stderr, "hssl_ctx_init failed!\n");
  173. return -1;
  174. }
  175. }
  176. tls = true;
  177. return 0;
  178. }
  179. void setConnectTimeout(int ms) {
  180. connect_timeout = ms;
  181. }
  182. void setReconnect(ReconnectInfo* info) {
  183. if (info) {
  184. enable_reconnect = true;
  185. reconnect_info = *info;
  186. } else {
  187. enable_reconnect = false;
  188. }
  189. }
  190. void setUnpack(unpack_setting_t* setting) {
  191. if (setting) {
  192. enable_unpack = true;
  193. unpack_setting = *setting;
  194. } else {
  195. enable_unpack = false;
  196. }
  197. }
  198. public:
  199. TSocketChannelPtr channel;
  200. sockaddr_u peeraddr;
  201. bool tls;
  202. int connect_timeout;
  203. bool enable_reconnect;
  204. ReconnectInfo reconnect_info;
  205. bool enable_unpack;
  206. unpack_setting_t unpack_setting;
  207. // Callback
  208. std::function<void(const TSocketChannelPtr&)> onConnection;
  209. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  210. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  211. private:
  212. EventLoopThread loop_thread;
  213. };
  214. typedef TcpClientTmpl<SocketChannel> TcpClient;
  215. }
  216. #endif // HV_TCP_CLIENT_HPP_