1
0

TcpClient.h 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 = 5000;
  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(&peeraddr, 0, sizeof(peeraddr));
  32. int ret = sockaddr_set_ipport(&peeraddr, remote_host, remote_port);
  33. if (ret != 0) {
  34. return -1;
  35. }
  36. return createsocket(&peeraddr.sa);
  37. }
  38. int createsocket(struct sockaddr* peeraddr) {
  39. int connfd = socket(peeraddr->sa_family, SOCK_STREAM, 0);
  40. // SOCKADDR_PRINT(peeraddr);
  41. if (connfd < 0) {
  42. perror("socket");
  43. return -2;
  44. }
  45. hio_t* io = hio_get(loop_thread.hloop(), connfd);
  46. assert(io != NULL);
  47. hio_set_peeraddr(io, peeraddr, SOCKADDR_LEN(peeraddr));
  48. channel.reset(new TSocketChannel(io));
  49. return connfd;
  50. }
  51. // closesocket thread-safe
  52. void closesocket() {
  53. setReconnect(NULL);
  54. if (channel) {
  55. channel->close(true);
  56. }
  57. }
  58. int startConnect() {
  59. assert(channel != NULL);
  60. if (connect_timeout) {
  61. channel->setConnectTimeout(connect_timeout);
  62. }
  63. if (tls) {
  64. channel->enableSSL();
  65. if (tls_setting) {
  66. channel->newSslCtx(tls_setting);
  67. }
  68. }
  69. channel->onconnect = [this]() {
  70. if (unpack_setting) {
  71. channel->setUnpack(unpack_setting);
  72. }
  73. channel->startRead();
  74. if (onConnection) {
  75. onConnection(channel);
  76. }
  77. if (reconn_setting) {
  78. reconn_setting_reset(reconn_setting);
  79. }
  80. };
  81. channel->onread = [this](Buffer* buf) {
  82. if (onMessage) {
  83. onMessage(channel, buf);
  84. }
  85. };
  86. channel->onwrite = [this](Buffer* buf) {
  87. if (onWriteComplete) {
  88. onWriteComplete(channel, buf);
  89. }
  90. };
  91. channel->onclose = [this]() {
  92. if (onConnection) {
  93. onConnection(channel);
  94. }
  95. // reconnect
  96. if (reconn_setting) {
  97. startReconnect();
  98. } else {
  99. channel = NULL;
  100. // NOTE: channel should be destroyed,
  101. // so in this lambda function, no code should be added below.
  102. }
  103. };
  104. return channel->startConnect();
  105. }
  106. int startReconnect() {
  107. if (!reconn_setting) return -1;
  108. if (!reconn_setting_can_retry(reconn_setting)) return -2;
  109. uint32_t delay = reconn_setting_calc_delay(reconn_setting);
  110. loop_thread.loop()->setTimeout(delay, [this](TimerID timerID){
  111. hlogi("reconnect... cnt=%d, delay=%d", reconn_setting->cur_retry_cnt, reconn_setting->cur_delay);
  112. if (createsocket(&peeraddr.sa) < 0) return;
  113. startConnect();
  114. });
  115. return 0;
  116. }
  117. void start(bool wait_threads_started = true) {
  118. loop_thread.start(wait_threads_started, std::bind(&TcpClientTmpl::startConnect, this));
  119. }
  120. // stop thread-safe
  121. void stop(bool wait_threads_stopped = true) {
  122. setReconnect(NULL);
  123. loop_thread.stop(wait_threads_stopped);
  124. }
  125. bool isConnected() {
  126. if (channel == NULL) return false;
  127. return channel->isConnected();
  128. }
  129. // send thread-safe
  130. int send(const void* data, int size) {
  131. if (!isConnected()) return -1;
  132. return channel->write(data, size);
  133. }
  134. int send(Buffer* buf) {
  135. return send(buf->data(), buf->size());
  136. }
  137. int send(const std::string& str) {
  138. return send(str.data(), str.size());
  139. }
  140. int withTLS(hssl_ctx_opt_t* opt = NULL) {
  141. tls = true;
  142. if (opt) {
  143. if (tls_setting == NULL) {
  144. HV_ALLOC_SIZEOF(tls_setting);
  145. }
  146. opt->endpoint = HSSL_CLIENT;
  147. *tls_setting = *opt;
  148. }
  149. return 0;
  150. }
  151. void setConnectTimeout(int ms) {
  152. connect_timeout = ms;
  153. }
  154. void setReconnect(reconn_setting_t* setting) {
  155. if (setting == NULL) {
  156. HV_FREE(reconn_setting);
  157. return;
  158. }
  159. if (reconn_setting == NULL) {
  160. HV_ALLOC_SIZEOF(reconn_setting);
  161. }
  162. *reconn_setting = *setting;
  163. }
  164. bool isReconnect() {
  165. return reconn_setting && reconn_setting->cur_retry_cnt > 0;
  166. }
  167. void setUnpack(unpack_setting_t* setting) {
  168. if (setting == NULL) {
  169. HV_FREE(unpack_setting);
  170. return;
  171. }
  172. if (unpack_setting == NULL) {
  173. HV_ALLOC_SIZEOF(unpack_setting);
  174. }
  175. *unpack_setting = *setting;
  176. }
  177. public:
  178. TSocketChannelPtr channel;
  179. sockaddr_u peeraddr;
  180. int connect_timeout;
  181. bool tls;
  182. hssl_ctx_opt_t* tls_setting;
  183. reconn_setting_t* reconn_setting;
  184. unpack_setting_t* unpack_setting;
  185. // Callback
  186. std::function<void(const TSocketChannelPtr&)> onConnection;
  187. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  188. // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written.
  189. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  190. private:
  191. EventLoopThread loop_thread;
  192. };
  193. typedef TcpClientTmpl<SocketChannel> TcpClient;
  194. }
  195. #endif // HV_TCP_CLIENT_HPP_