TcpClient.h 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. int ret = channel->newSslCtx(tls_setting);
  79. if (ret != 0) {
  80. hloge("new SSL_CTX failed: %d", ret);
  81. closesocket();
  82. return ret;
  83. }
  84. }
  85. if (!is_ipaddr(remote_host.c_str())) {
  86. channel->setHostname(remote_host);
  87. }
  88. }
  89. channel->onconnect = [this]() {
  90. if (unpack_setting) {
  91. channel->setUnpack(unpack_setting);
  92. }
  93. channel->startRead();
  94. if (onConnection) {
  95. onConnection(channel);
  96. }
  97. if (reconn_setting) {
  98. reconn_setting_reset(reconn_setting);
  99. }
  100. };
  101. channel->onread = [this](Buffer* buf) {
  102. if (onMessage) {
  103. onMessage(channel, buf);
  104. }
  105. };
  106. channel->onwrite = [this](Buffer* buf) {
  107. if (onWriteComplete) {
  108. onWriteComplete(channel, buf);
  109. }
  110. };
  111. channel->onclose = [this]() {
  112. if (onConnection) {
  113. onConnection(channel);
  114. }
  115. // reconnect
  116. if (reconn_setting) {
  117. startReconnect();
  118. }
  119. };
  120. return channel->startConnect();
  121. }
  122. int startReconnect() {
  123. if (!reconn_setting) return -1;
  124. if (!reconn_setting_can_retry(reconn_setting)) return -2;
  125. uint32_t delay = reconn_setting_calc_delay(reconn_setting);
  126. loop_->setTimeout(delay, [this](TimerID timerID){
  127. hlogi("reconnect... cnt=%d, delay=%d", reconn_setting->cur_retry_cnt, reconn_setting->cur_delay);
  128. startConnect();
  129. });
  130. return 0;
  131. }
  132. // start thread-safe
  133. void start() {
  134. loop_->runInLoop(std::bind(&TcpClientEventLoopTmpl::startConnect, this));
  135. }
  136. bool isConnected() {
  137. if (channel == NULL) return false;
  138. return channel->isConnected();
  139. }
  140. // send thread-safe
  141. int send(const void* data, int size) {
  142. if (!isConnected()) return -1;
  143. return channel->write(data, size);
  144. }
  145. int send(Buffer* buf) {
  146. return send(buf->data(), buf->size());
  147. }
  148. int send(const std::string& str) {
  149. return send(str.data(), str.size());
  150. }
  151. int withTLS(hssl_ctx_opt_t* opt = NULL) {
  152. tls = true;
  153. if (opt) {
  154. if (tls_setting == NULL) {
  155. HV_ALLOC_SIZEOF(tls_setting);
  156. }
  157. opt->endpoint = HSSL_CLIENT;
  158. *tls_setting = *opt;
  159. }
  160. return 0;
  161. }
  162. void setConnectTimeout(int ms) {
  163. connect_timeout = ms;
  164. }
  165. void setReconnect(reconn_setting_t* setting) {
  166. if (setting == NULL) {
  167. HV_FREE(reconn_setting);
  168. return;
  169. }
  170. if (reconn_setting == NULL) {
  171. HV_ALLOC_SIZEOF(reconn_setting);
  172. }
  173. *reconn_setting = *setting;
  174. }
  175. bool isReconnect() {
  176. return reconn_setting && reconn_setting->cur_retry_cnt > 0;
  177. }
  178. void setUnpack(unpack_setting_t* setting) {
  179. if (setting == NULL) {
  180. HV_FREE(unpack_setting);
  181. return;
  182. }
  183. if (unpack_setting == NULL) {
  184. HV_ALLOC_SIZEOF(unpack_setting);
  185. }
  186. *unpack_setting = *setting;
  187. }
  188. public:
  189. TSocketChannelPtr channel;
  190. std::string remote_host;
  191. int remote_port;
  192. sockaddr_u remote_addr;
  193. int connect_timeout;
  194. bool tls;
  195. hssl_ctx_opt_t* tls_setting;
  196. reconn_setting_t* reconn_setting;
  197. unpack_setting_t* unpack_setting;
  198. // Callback
  199. std::function<void(const TSocketChannelPtr&)> onConnection;
  200. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  201. // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written.
  202. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  203. private:
  204. EventLoopPtr loop_;
  205. };
  206. template<class TSocketChannel = SocketChannel>
  207. class TcpClientTmpl : private EventLoopThread, public TcpClientEventLoopTmpl<TSocketChannel> {
  208. public:
  209. TcpClientTmpl(EventLoopPtr loop = NULL)
  210. : EventLoopThread(loop)
  211. , TcpClientEventLoopTmpl<TSocketChannel>(EventLoopThread::loop())
  212. {}
  213. virtual ~TcpClientTmpl() {
  214. stop(true);
  215. }
  216. const EventLoopPtr& loop() {
  217. return EventLoopThread::loop();
  218. }
  219. // start thread-safe
  220. void start(bool wait_threads_started = true) {
  221. if (isRunning()) {
  222. TcpClientEventLoopTmpl<TSocketChannel>::start();
  223. } else {
  224. EventLoopThread::start(wait_threads_started, std::bind(&TcpClientTmpl::startConnect, this));
  225. }
  226. }
  227. // stop thread-safe
  228. void stop(bool wait_threads_stopped = true) {
  229. TcpClientEventLoopTmpl<TSocketChannel>::closesocket();
  230. EventLoopThread::stop(wait_threads_stopped);
  231. }
  232. };
  233. typedef TcpClientTmpl<SocketChannel> TcpClient;
  234. }
  235. #endif // HV_TCP_CLIENT_HPP_