Channel.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #ifndef HV_CHANNEL_HPP_
  2. #define HV_CHANNEL_HPP_
  3. #include <string>
  4. #include <functional>
  5. #include <memory>
  6. #include "hloop.h"
  7. #include "hsocket.h"
  8. #include "Buffer.h"
  9. namespace hv {
  10. class Channel {
  11. public:
  12. Channel(hio_t* io = NULL) {
  13. io_ = io;
  14. fd_ = -1;
  15. id_ = 0;
  16. ctx_ = NULL;
  17. status = CLOSED;
  18. if (io) {
  19. fd_ = hio_fd(io);
  20. id_ = hio_id(io);
  21. ctx_ = hio_context(io);
  22. hio_set_context(io, this);
  23. if (hio_is_opened(io)) {
  24. status = OPENED;
  25. }
  26. if (hio_getcb_read(io) == NULL) {
  27. hio_setcb_read(io_, on_read);
  28. }
  29. if (hio_getcb_write(io) == NULL) {
  30. hio_setcb_write(io_, on_write);
  31. }
  32. if (hio_getcb_close(io) == NULL) {
  33. hio_setcb_close(io_, on_close);
  34. }
  35. }
  36. }
  37. virtual ~Channel() {
  38. if (isOpened()) {
  39. close();
  40. // NOTE: Detach after destructor to avoid triggering onclose
  41. if (io_ && id_ == hio_id(io_)) {
  42. hio_set_context(io_, NULL);
  43. }
  44. }
  45. }
  46. hio_t* io() { return io_; }
  47. int fd() { return fd_; }
  48. uint32_t id() { return id_; }
  49. int error() { return hio_error(io_); }
  50. // context
  51. void* context() {
  52. return ctx_;
  53. }
  54. void setContext(void* ctx) {
  55. ctx_ = ctx;
  56. }
  57. template<class T>
  58. T* newContext() {
  59. ctx_ = new T;
  60. return (T*)ctx_;
  61. }
  62. template<class T>
  63. T* getContext() {
  64. return (T*)ctx_;
  65. }
  66. template<class T>
  67. void deleteContext() {
  68. if (ctx_) {
  69. delete (T*)ctx_;
  70. ctx_ = NULL;
  71. }
  72. }
  73. // contextPtr
  74. std::shared_ptr<void> contextPtr() {
  75. return contextPtr_;
  76. }
  77. void setContextPtr(const std::shared_ptr<void>& ctx) {
  78. contextPtr_ = ctx;
  79. }
  80. void setContextPtr(std::shared_ptr<void>&& ctx) {
  81. contextPtr_ = std::move(ctx);
  82. }
  83. template<class T>
  84. std::shared_ptr<T> newContextPtr() {
  85. contextPtr_ = std::make_shared<T>();
  86. return std::static_pointer_cast<T>(contextPtr_);
  87. }
  88. template<class T>
  89. std::shared_ptr<T> getContextPtr() {
  90. return std::static_pointer_cast<T>(contextPtr_);
  91. }
  92. void deleteContextPtr() {
  93. contextPtr_.reset();
  94. }
  95. bool isOpened() {
  96. if (io_ == NULL || status >= DISCONNECTED) return false;
  97. return id_ == hio_id(io_) && hio_is_opened(io_);
  98. }
  99. bool isClosed() {
  100. return !isOpened();
  101. }
  102. int startRead() {
  103. if (!isOpened()) return -1;
  104. return hio_read_start(io_);
  105. }
  106. int stopRead() {
  107. if (!isOpened()) return -1;
  108. return hio_read_stop(io_);
  109. }
  110. int readOnce() {
  111. if (!isOpened()) return -1;
  112. return hio_read_once(io_);
  113. }
  114. int readString() {
  115. if (!isOpened()) return -1;
  116. return hio_readstring(io_);
  117. }
  118. int readLine() {
  119. if (!isOpened()) return -1;
  120. return hio_readline(io_);
  121. }
  122. int readBytes(int len) {
  123. if (!isOpened() || len <= 0) return -1;
  124. return hio_readbytes(io_, len);
  125. }
  126. // write thread-safe
  127. int write(const void* data, int size) {
  128. if (!isOpened()) return -1;
  129. return hio_write(io_, data, size);
  130. }
  131. int write(Buffer* buf) {
  132. return write(buf->data(), buf->size());
  133. }
  134. int write(const std::string& str) {
  135. return write(str.data(), str.size());
  136. }
  137. // iobuf setting
  138. void setMaxReadBufsize(uint32_t size) {
  139. if (io_ == NULL) return;
  140. hio_set_max_read_bufsize(io_, size);
  141. }
  142. void setMaxWriteBufsize(uint32_t size) {
  143. if (io_ == NULL) return;
  144. hio_set_max_write_bufsize(io_, size);
  145. }
  146. size_t writeBufsize() {
  147. if (io_ == NULL) return 0;
  148. return hio_write_bufsize(io_);
  149. }
  150. bool isWriteComplete() {
  151. return writeBufsize() == 0;
  152. }
  153. // close thread-safe
  154. int close(bool async = false) {
  155. if (isClosed()) return -1;
  156. status = CLOSED;
  157. return async ? hio_close_async(io_) : hio_close(io_);
  158. }
  159. public:
  160. hio_t* io_;
  161. int fd_;
  162. uint32_t id_;
  163. void* ctx_;
  164. enum Status {
  165. OPENED,
  166. CONNECTING,
  167. CONNECTED,
  168. DISCONNECTED,
  169. CLOSED,
  170. } status;
  171. std::function<void(Buffer*)> onread;
  172. // NOTE: Use Channel::isWriteComplete in onwrite callback to determine whether all data has been written.
  173. std::function<void(Buffer*)> onwrite;
  174. std::function<void()> onclose;
  175. std::shared_ptr<void> contextPtr_;
  176. private:
  177. static void on_read(hio_t* io, void* data, int readbytes) {
  178. Channel* channel = (Channel*)hio_context(io);
  179. if (channel && channel->onread) {
  180. Buffer buf(data, readbytes);
  181. channel->onread(&buf);
  182. }
  183. }
  184. static void on_write(hio_t* io, const void* data, int writebytes) {
  185. Channel* channel = (Channel*)hio_context(io);
  186. if (channel && channel->onwrite) {
  187. Buffer buf((void*)data, writebytes);
  188. channel->onwrite(&buf);
  189. }
  190. }
  191. static void on_close(hio_t* io) {
  192. Channel* channel = (Channel*)hio_context(io);
  193. if (channel) {
  194. channel->status = CLOSED;
  195. if (channel->onclose) {
  196. channel->onclose();
  197. }
  198. }
  199. }
  200. };
  201. class SocketChannel : public Channel {
  202. public:
  203. std::function<void()> onconnect; // only for TcpClient
  204. std::function<void()> heartbeat;
  205. SocketChannel(hio_t* io) : Channel(io) {
  206. }
  207. virtual ~SocketChannel() {}
  208. // SSL/TLS
  209. int enableSSL() {
  210. if (io_ == NULL) return -1;
  211. return hio_enable_ssl(io_);
  212. }
  213. bool isSSL() {
  214. if (io_ == NULL) return false;
  215. return hio_is_ssl(io_);
  216. }
  217. int setSSL(hssl_t ssl) {
  218. if (io_ == NULL) return -1;
  219. return hio_set_ssl(io_, ssl);
  220. }
  221. int setSslCtx(hssl_ctx_t ssl_ctx) {
  222. if (io_ == NULL) return -1;
  223. return hio_set_ssl_ctx(io_, ssl_ctx);
  224. }
  225. int newSslCtx(hssl_ctx_opt_t* opt) {
  226. if (io_ == NULL) return -1;
  227. return hio_new_ssl_ctx(io_, opt);
  228. }
  229. // for hssl_set_sni_hostname
  230. int setHostname(const std::string& hostname) {
  231. if (io_ == NULL) return -1;
  232. return hio_set_hostname(io_, hostname.c_str());
  233. }
  234. // timeout
  235. void setConnectTimeout(int timeout_ms) {
  236. if (io_ == NULL) return;
  237. hio_set_connect_timeout(io_, timeout_ms);
  238. }
  239. void setCloseTimeout(int timeout_ms) {
  240. if (io_ == NULL) return;
  241. hio_set_close_timeout(io_, timeout_ms);
  242. }
  243. void setReadTimeout(int timeout_ms) {
  244. if (io_ == NULL) return;
  245. hio_set_read_timeout(io_, timeout_ms);
  246. }
  247. void setWriteTimeout(int timeout_ms) {
  248. if (io_ == NULL) return;
  249. hio_set_write_timeout(io_, timeout_ms);
  250. }
  251. void setKeepaliveTimeout(int timeout_ms) {
  252. if (io_ == NULL) return;
  253. hio_set_keepalive_timeout(io_, timeout_ms);
  254. }
  255. // heartbeat
  256. // NOTE: Beware of circular reference problems caused by passing SocketChannelPtr by value.
  257. void setHeartbeat(int interval_ms, std::function<void()> fn) {
  258. if (io_ == NULL) return;
  259. heartbeat = std::move(fn);
  260. hio_set_heartbeat(io_, interval_ms, send_heartbeat);
  261. }
  262. // unpack
  263. void setUnpack(unpack_setting_t* setting) {
  264. if (io_ == NULL) return;
  265. hio_set_unpack(io_, setting);
  266. }
  267. int startConnect(int port, const char* host = "127.0.0.1") {
  268. sockaddr_u peeraddr;
  269. memset(&peeraddr, 0, sizeof(peeraddr));
  270. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  271. if (ret != 0) {
  272. // hloge("unknown host %s", host);
  273. return ret;
  274. }
  275. return startConnect(&peeraddr.sa);
  276. }
  277. int startConnect(struct sockaddr* peeraddr) {
  278. if (io_ == NULL) return -1;
  279. hio_set_peeraddr(io_, peeraddr, SOCKADDR_LEN(peeraddr));
  280. return startConnect();
  281. }
  282. int startConnect() {
  283. if (io_ == NULL) return -1;
  284. status = CONNECTING;
  285. hio_setcb_connect(io_, on_connect);
  286. return hio_connect(io_);
  287. }
  288. bool isConnected() {
  289. return status == CONNECTED && isOpened();
  290. }
  291. std::string localaddr() {
  292. if (io_ == NULL) return "";
  293. struct sockaddr* addr = hio_localaddr(io_);
  294. char buf[SOCKADDR_STRLEN] = {0};
  295. return SOCKADDR_STR(addr, buf);
  296. }
  297. std::string peeraddr() {
  298. if (io_ == NULL) return "";
  299. struct sockaddr* addr = hio_peeraddr(io_);
  300. char buf[SOCKADDR_STRLEN] = {0};
  301. return SOCKADDR_STR(addr, buf);
  302. }
  303. private:
  304. static void on_connect(hio_t* io) {
  305. SocketChannel* channel = (SocketChannel*)hio_context(io);
  306. if (channel) {
  307. channel->status = CONNECTED;
  308. if (channel->onconnect) {
  309. channel->onconnect();
  310. }
  311. }
  312. }
  313. static void send_heartbeat(hio_t* io) {
  314. SocketChannel* channel = (SocketChannel*)hio_context(io);
  315. if (channel && channel->heartbeat) {
  316. channel->heartbeat();
  317. }
  318. }
  319. };
  320. typedef std::shared_ptr<Channel> ChannelPtr;
  321. typedef std::shared_ptr<SocketChannel> SocketChannelPtr;
  322. }
  323. #endif // HV_CHANNEL_HPP_