TcpClient.h 7.7 KB

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