TcpClient.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. template<class TSocketChannel = SocketChannel>
  10. class TcpClientTmpl {
  11. public:
  12. typedef std::shared_ptr<TSocketChannel> TSocketChannelPtr;
  13. TcpClientTmpl() {
  14. connect_timeout = HIO_DEFAULT_CONNECT_TIMEOUT;
  15. tls = false;
  16. tls_setting = NULL;
  17. reconn_setting = NULL;
  18. unpack_setting = NULL;
  19. }
  20. virtual ~TcpClientTmpl() {
  21. HV_FREE(tls_setting);
  22. HV_FREE(reconn_setting);
  23. HV_FREE(unpack_setting);
  24. }
  25. const EventLoopPtr& loop() {
  26. return loop_thread.loop();
  27. }
  28. //NOTE: By default, not bind local port. If necessary, you can call system api bind() after createsocket().
  29. //@retval >=0 connfd, <0 error
  30. int createsocket(int remote_port, const char* remote_host = "127.0.0.1") {
  31. memset(&remote_addr, 0, sizeof(remote_addr));
  32. int ret = sockaddr_set_ipport(&remote_addr, remote_host, remote_port);
  33. if (ret != 0) {
  34. return -1;
  35. }
  36. this->remote_host = remote_host;
  37. this->remote_port = remote_port;
  38. return createsocket(&remote_addr.sa);
  39. }
  40. int createsocket(struct sockaddr* remote_addr) {
  41. int connfd = socket(remote_addr->sa_family, SOCK_STREAM, 0);
  42. // SOCKADDR_PRINT(remote_addr);
  43. if (connfd < 0) {
  44. perror("socket");
  45. return -2;
  46. }
  47. hio_t* io = hio_get(loop_thread.hloop(), connfd);
  48. assert(io != NULL);
  49. hio_set_peeraddr(io, remote_addr, SOCKADDR_LEN(remote_addr));
  50. channel.reset(new TSocketChannel(io));
  51. return connfd;
  52. }
  53. // closesocket thread-safe
  54. void closesocket() {
  55. setReconnect(NULL);
  56. if (channel) {
  57. channel->close(true);
  58. }
  59. }
  60. int startConnect() {
  61. assert(channel != NULL);
  62. if (connect_timeout) {
  63. channel->setConnectTimeout(connect_timeout);
  64. }
  65. if (tls) {
  66. channel->enableSSL();
  67. if (tls_setting) {
  68. channel->newSslCtx(tls_setting);
  69. }
  70. if (!is_ipaddr(remote_host.c_str())) {
  71. channel->setHostname(remote_host);
  72. }
  73. }
  74. channel->onconnect = [this]() {
  75. if (unpack_setting) {
  76. channel->setUnpack(unpack_setting);
  77. }
  78. channel->startRead();
  79. if (onConnection) {
  80. onConnection(channel);
  81. }
  82. if (reconn_setting) {
  83. reconn_setting_reset(reconn_setting);
  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 (reconn_setting) {
  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 (!reconn_setting) return -1;
  113. if (!reconn_setting_can_retry(reconn_setting)) return -2;
  114. uint32_t delay = reconn_setting_calc_delay(reconn_setting);
  115. loop_thread.loop()->setTimeout(delay, [this](TimerID timerID){
  116. hlogi("reconnect... cnt=%d, delay=%d", reconn_setting->cur_retry_cnt, reconn_setting->cur_delay);
  117. if (createsocket(&remote_addr.sa) < 0) return;
  118. startConnect();
  119. });
  120. return 0;
  121. }
  122. void start(bool wait_threads_started = true) {
  123. loop_thread.start(wait_threads_started, std::bind(&TcpClientTmpl::startConnect, this));
  124. }
  125. // stop thread-safe
  126. void stop(bool wait_threads_stopped = true) {
  127. setReconnect(NULL);
  128. loop_thread.stop(wait_threads_stopped);
  129. }
  130. bool isConnected() {
  131. if (channel == NULL) return false;
  132. return channel->isConnected();
  133. }
  134. // send thread-safe
  135. int send(const void* data, int size) {
  136. if (!isConnected()) return -1;
  137. return channel->write(data, size);
  138. }
  139. int send(Buffer* buf) {
  140. return send(buf->data(), buf->size());
  141. }
  142. int send(const std::string& str) {
  143. return send(str.data(), str.size());
  144. }
  145. int withTLS(hssl_ctx_opt_t* opt = NULL) {
  146. tls = true;
  147. if (opt) {
  148. if (tls_setting == NULL) {
  149. HV_ALLOC_SIZEOF(tls_setting);
  150. }
  151. opt->endpoint = HSSL_CLIENT;
  152. *tls_setting = *opt;
  153. }
  154. return 0;
  155. }
  156. void setConnectTimeout(int ms) {
  157. connect_timeout = ms;
  158. }
  159. void setReconnect(reconn_setting_t* setting) {
  160. if (setting == NULL) {
  161. HV_FREE(reconn_setting);
  162. return;
  163. }
  164. if (reconn_setting == NULL) {
  165. HV_ALLOC_SIZEOF(reconn_setting);
  166. }
  167. *reconn_setting = *setting;
  168. }
  169. bool isReconnect() {
  170. return reconn_setting && reconn_setting->cur_retry_cnt > 0;
  171. }
  172. void setUnpack(unpack_setting_t* setting) {
  173. if (setting == NULL) {
  174. HV_FREE(unpack_setting);
  175. return;
  176. }
  177. if (unpack_setting == NULL) {
  178. HV_ALLOC_SIZEOF(unpack_setting);
  179. }
  180. *unpack_setting = *setting;
  181. }
  182. public:
  183. TSocketChannelPtr channel;
  184. std::string remote_host;
  185. int remote_port;
  186. sockaddr_u remote_addr;
  187. int connect_timeout;
  188. bool tls;
  189. hssl_ctx_opt_t* tls_setting;
  190. reconn_setting_t* reconn_setting;
  191. unpack_setting_t* unpack_setting;
  192. // Callback
  193. std::function<void(const TSocketChannelPtr&)> onConnection;
  194. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  195. // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written.
  196. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  197. private:
  198. EventLoopThread loop_thread;
  199. };
  200. typedef TcpClientTmpl<SocketChannel> TcpClient;
  201. }
  202. #endif // HV_TCP_CLIENT_HPP_