1
0

TcpClient.h 8.6 KB

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