TcpClient.h 7.2 KB

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