TcpClient.h 7.4 KB

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