TcpServer.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #ifndef HV_TCP_SERVER_HPP_
  2. #define HV_TCP_SERVER_HPP_
  3. #include "hsocket.h"
  4. #include "hssl.h"
  5. #include "hlog.h"
  6. #include "EventLoopThreadPool.h"
  7. #include "Channel.h"
  8. namespace hv {
  9. template<class TSocketChannel = SocketChannel>
  10. class TcpServerEventLoopTmpl {
  11. public:
  12. typedef std::shared_ptr<TSocketChannel> TSocketChannelPtr;
  13. TcpServerEventLoopTmpl(EventLoopPtr loop = NULL) {
  14. acceptor_loop = loop ? loop : std::make_shared<EventLoop>();
  15. port = 0;
  16. listenfd = -1;
  17. tls = false;
  18. tls_setting = NULL;
  19. unpack_setting = NULL;
  20. max_connections = 0xFFFFFFFF;
  21. load_balance = LB_RoundRobin;
  22. }
  23. virtual ~TcpServerEventLoopTmpl() {
  24. HV_FREE(tls_setting);
  25. HV_FREE(unpack_setting);
  26. }
  27. EventLoopPtr loop(int idx = -1) {
  28. EventLoopPtr worker_loop = worker_threads.loop(idx);
  29. if (worker_loop == NULL) {
  30. worker_loop = acceptor_loop;
  31. }
  32. return worker_loop;
  33. }
  34. //@retval >=0 listenfd, <0 error
  35. int createsocket(int port, const char* host = "0.0.0.0") {
  36. listenfd = Listen(port, host);
  37. if (listenfd < 0) return listenfd;
  38. this->host = host;
  39. this->port = port;
  40. return listenfd;
  41. }
  42. // closesocket thread-safe
  43. void closesocket() {
  44. if (listenfd >= 0) {
  45. hloop_t* loop = acceptor_loop->loop();
  46. if (loop) {
  47. hio_t* listenio = hio_get(loop, listenfd);
  48. assert(listenio != NULL);
  49. hio_close_async(listenio);
  50. }
  51. listenfd = -1;
  52. }
  53. }
  54. void setMaxConnectionNum(uint32_t num) {
  55. max_connections = num;
  56. }
  57. void setLoadBalance(load_balance_e lb) {
  58. load_balance = lb;
  59. }
  60. // NOTE: totalThreadNum = 1 acceptor_thread + N worker_threads (N can be 0)
  61. void setThreadNum(int num) {
  62. worker_threads.setThreadNum(num);
  63. }
  64. int startAccept() {
  65. if (listenfd < 0) {
  66. listenfd = createsocket(port, host.c_str());
  67. if (listenfd < 0) {
  68. hloge("createsocket %s:%d return %d!\n", host.c_str(), port, listenfd);
  69. return listenfd;
  70. }
  71. }
  72. hloop_t* loop = acceptor_loop->loop();
  73. if (loop == NULL) return -2;
  74. hio_t* listenio = haccept(loop, listenfd, onAccept);
  75. assert(listenio != NULL);
  76. hevent_set_userdata(listenio, this);
  77. if (tls) {
  78. hio_enable_ssl(listenio);
  79. if (tls_setting) {
  80. int ret = hio_new_ssl_ctx(listenio, tls_setting);
  81. if (ret != 0) {
  82. hloge("new SSL_CTX failed: %d", ret);
  83. closesocket();
  84. return ret;
  85. }
  86. }
  87. }
  88. return 0;
  89. }
  90. int stopAccept() {
  91. if (listenfd < 0) return -1;
  92. hloop_t* loop = acceptor_loop->loop();
  93. if (loop == NULL) return -2;
  94. hio_t* listenio = hio_get(loop, listenfd);
  95. assert(listenio != NULL);
  96. return hio_del(listenio, HV_READ);
  97. }
  98. // start thread-safe
  99. void start(bool wait_threads_started = true) {
  100. if (worker_threads.threadNum() > 0) {
  101. worker_threads.start(wait_threads_started);
  102. }
  103. acceptor_loop->runInLoop(std::bind(&TcpServerEventLoopTmpl::startAccept, this));
  104. }
  105. // stop thread-safe
  106. void stop(bool wait_threads_stopped = true) {
  107. closesocket();
  108. if (worker_threads.threadNum() > 0) {
  109. worker_threads.stop(wait_threads_stopped);
  110. }
  111. }
  112. int withTLS(hssl_ctx_opt_t* opt = NULL) {
  113. tls = true;
  114. if (opt) {
  115. if (tls_setting == NULL) {
  116. HV_ALLOC_SIZEOF(tls_setting);
  117. }
  118. opt->endpoint = HSSL_SERVER;
  119. *tls_setting = *opt;
  120. }
  121. return 0;
  122. }
  123. void setUnpack(unpack_setting_t* setting) {
  124. if (setting == NULL) {
  125. HV_FREE(unpack_setting);
  126. return;
  127. }
  128. if (unpack_setting == NULL) {
  129. HV_ALLOC_SIZEOF(unpack_setting);
  130. }
  131. *unpack_setting = *setting;
  132. }
  133. // channel
  134. const TSocketChannelPtr& addChannel(hio_t* io) {
  135. uint32_t id = hio_id(io);
  136. auto channel = std::make_shared<TSocketChannel>(io);
  137. std::lock_guard<std::mutex> locker(mutex_);
  138. channels[id] = channel;
  139. return channels[id];
  140. }
  141. TSocketChannelPtr getChannelById(uint32_t id) {
  142. std::lock_guard<std::mutex> locker(mutex_);
  143. auto iter = channels.find(id);
  144. return iter != channels.end() ? iter->second : NULL;
  145. }
  146. void removeChannel(const TSocketChannelPtr& channel) {
  147. uint32_t id = channel->id();
  148. std::lock_guard<std::mutex> locker(mutex_);
  149. channels.erase(id);
  150. }
  151. size_t connectionNum() {
  152. std::lock_guard<std::mutex> locker(mutex_);
  153. return channels.size();
  154. }
  155. int foreachChannel(std::function<void(const TSocketChannelPtr& channel)> fn) {
  156. std::lock_guard<std::mutex> locker(mutex_);
  157. for (auto& pair : channels) {
  158. fn(pair.second);
  159. }
  160. return channels.size();
  161. }
  162. // broadcast thread-safe
  163. int broadcast(const void* data, int size) {
  164. return foreachChannel([data, size](const TSocketChannelPtr& channel) {
  165. channel->write(data, size);
  166. });
  167. }
  168. int broadcast(const std::string& str) {
  169. return broadcast(str.data(), str.size());
  170. }
  171. private:
  172. static void newConnEvent(hio_t* connio) {
  173. TcpServerEventLoopTmpl* server = (TcpServerEventLoopTmpl*)hevent_userdata(connio);
  174. if (server->connectionNum() >= server->max_connections) {
  175. hlogw("over max_connections");
  176. hio_close(connio);
  177. return;
  178. }
  179. // NOTE: attach to worker loop
  180. EventLoop* worker_loop = currentThreadEventLoop;
  181. assert(worker_loop != NULL);
  182. hio_attach(worker_loop->loop(), connio);
  183. const TSocketChannelPtr& channel = server->addChannel(connio);
  184. channel->status = SocketChannel::CONNECTED;
  185. channel->onread = [server, &channel](Buffer* buf) {
  186. if (server->onMessage) {
  187. server->onMessage(channel, buf);
  188. }
  189. };
  190. channel->onwrite = [server, &channel](Buffer* buf) {
  191. if (server->onWriteComplete) {
  192. server->onWriteComplete(channel, buf);
  193. }
  194. };
  195. channel->onclose = [server, &channel]() {
  196. EventLoop* worker_loop = currentThreadEventLoop;
  197. assert(worker_loop != NULL);
  198. --worker_loop->connectionNum;
  199. channel->status = SocketChannel::CLOSED;
  200. if (server->onConnection) {
  201. server->onConnection(channel);
  202. }
  203. server->removeChannel(channel);
  204. // NOTE: After removeChannel, channel may be destroyed,
  205. // so in this lambda function, no code should be added below.
  206. };
  207. if (server->unpack_setting) {
  208. channel->setUnpack(server->unpack_setting);
  209. }
  210. channel->startRead();
  211. if (server->onConnection) {
  212. server->onConnection(channel);
  213. }
  214. }
  215. static void onAccept(hio_t* connio) {
  216. TcpServerEventLoopTmpl* server = (TcpServerEventLoopTmpl*)hevent_userdata(connio);
  217. // NOTE: detach from acceptor loop
  218. hio_detach(connio);
  219. EventLoopPtr worker_loop = server->worker_threads.nextLoop(server->load_balance);
  220. if (worker_loop == NULL) {
  221. worker_loop = server->acceptor_loop;
  222. }
  223. ++worker_loop->connectionNum;
  224. worker_loop->runInLoop(std::bind(&TcpServerEventLoopTmpl::newConnEvent, connio));
  225. }
  226. public:
  227. std::string host;
  228. int port;
  229. int listenfd;
  230. bool tls;
  231. hssl_ctx_opt_t* tls_setting;
  232. unpack_setting_t* unpack_setting;
  233. // Callback
  234. std::function<void(const TSocketChannelPtr&)> onConnection;
  235. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  236. // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written.
  237. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  238. uint32_t max_connections;
  239. load_balance_e load_balance;
  240. private:
  241. // id => TSocketChannelPtr
  242. std::map<uint32_t, TSocketChannelPtr> channels; // GUAREDE_BY(mutex_)
  243. std::mutex mutex_;
  244. EventLoopPtr acceptor_loop;
  245. EventLoopThreadPool worker_threads;
  246. };
  247. template<class TSocketChannel = SocketChannel>
  248. class TcpServerTmpl : private EventLoopThread, public TcpServerEventLoopTmpl<TSocketChannel> {
  249. public:
  250. TcpServerTmpl(EventLoopPtr loop = NULL)
  251. : EventLoopThread(loop)
  252. , TcpServerEventLoopTmpl<TSocketChannel>(EventLoopThread::loop())
  253. , is_loop_owner(loop == NULL)
  254. {}
  255. virtual ~TcpServerTmpl() {
  256. stop(true);
  257. }
  258. EventLoopPtr loop(int idx = -1) {
  259. return TcpServerEventLoopTmpl<TSocketChannel>::loop(idx);
  260. }
  261. // start thread-safe
  262. void start(bool wait_threads_started = true) {
  263. TcpServerEventLoopTmpl<TSocketChannel>::start(wait_threads_started);
  264. EventLoopThread::start(wait_threads_started);
  265. }
  266. // stop thread-safe
  267. void stop(bool wait_threads_stopped = true) {
  268. if (is_loop_owner) {
  269. EventLoopThread::stop(wait_threads_stopped);
  270. }
  271. TcpServerEventLoopTmpl<TSocketChannel>::stop(wait_threads_stopped);
  272. }
  273. private:
  274. bool is_loop_owner;
  275. };
  276. typedef TcpServerTmpl<SocketChannel> TcpServer;
  277. }
  278. #endif // HV_TCP_SERVER_HPP_