1
0

TcpClient.h 5.7 KB

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