1
0

TcpServer.h 9.4 KB

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