TcpServer.h 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 TcpServerTmpl {
  11. public:
  12. typedef std::shared_ptr<TSocketChannel> TSocketChannelPtr;
  13. TcpServerTmpl() {
  14. listenfd = -1;
  15. tls = false;
  16. unpack_setting.mode = UNPACK_MODE_NONE;
  17. max_connections = 0xFFFFFFFF;
  18. }
  19. virtual ~TcpServerTmpl() {
  20. }
  21. EventLoopPtr loop(int idx = -1) {
  22. return worker_threads.loop(idx);
  23. }
  24. //@retval >=0 listenfd, <0 error
  25. int createsocket(int port, const char* host = "0.0.0.0") {
  26. listenfd = Listen(port, host);
  27. return listenfd;
  28. }
  29. // closesocket thread-safe
  30. void closesocket() {
  31. if (listenfd >= 0) {
  32. hio_close_async(hio_get(acceptor_thread.hloop(), listenfd));
  33. listenfd = -1;
  34. }
  35. }
  36. void setMaxConnectionNum(uint32_t num) {
  37. max_connections = num;
  38. }
  39. // NOTE: totalThreadNum = 1 acceptor_thread + N worker_threads (N can be 0)
  40. void setThreadNum(int num) {
  41. worker_threads.setThreadNum(num);
  42. }
  43. int startAccept() {
  44. assert(listenfd >= 0);
  45. hio_t* listenio = haccept(acceptor_thread.hloop(), listenfd, onAccept);
  46. hevent_set_userdata(listenio, this);
  47. if (tls) {
  48. hio_enable_ssl(listenio);
  49. }
  50. return 0;
  51. }
  52. void start(bool wait_threads_started = true) {
  53. if (worker_threads.threadNum() > 0) {
  54. worker_threads.start(wait_threads_started);
  55. }
  56. acceptor_thread.start(wait_threads_started, std::bind(&TcpServerTmpl::startAccept, this));
  57. }
  58. // stop thread-safe
  59. void stop(bool wait_threads_stopped = true) {
  60. acceptor_thread.stop(wait_threads_stopped);
  61. if (worker_threads.threadNum() > 0) {
  62. worker_threads.stop(wait_threads_stopped);
  63. }
  64. }
  65. int withTLS(hssl_ctx_opt_t* opt = NULL) {
  66. tls = true;
  67. if (opt) {
  68. opt->endpoint = HSSL_SERVER;
  69. if (hssl_ctx_init(opt) == NULL) {
  70. fprintf(stderr, "hssl_ctx_init failed!\n");
  71. return -1;
  72. }
  73. }
  74. return 0;
  75. }
  76. void setUnpack(unpack_setting_t* setting) {
  77. if (setting) {
  78. unpack_setting = *setting;
  79. } else {
  80. unpack_setting.mode = UNPACK_MODE_NONE;
  81. }
  82. }
  83. // channel
  84. const TSocketChannelPtr& addChannel(hio_t* io) {
  85. uint32_t id = hio_id(io);
  86. auto channel = TSocketChannelPtr(new TSocketChannel(io));
  87. std::lock_guard<std::mutex> locker(mutex_);
  88. channels[id] = channel;
  89. return channels[id];
  90. }
  91. TSocketChannelPtr getChannelById(uint32_t id) {
  92. std::lock_guard<std::mutex> locker(mutex_);
  93. auto iter = channels.find(id);
  94. return iter != channels.end() ? iter->second : NULL;
  95. }
  96. void removeChannel(const TSocketChannelPtr& channel) {
  97. uint32_t id = channel->id();
  98. std::lock_guard<std::mutex> locker(mutex_);
  99. channels.erase(id);
  100. }
  101. size_t connectionNum() {
  102. std::lock_guard<std::mutex> locker(mutex_);
  103. return channels.size();
  104. }
  105. int foreachChannel(std::function<void(const TSocketChannelPtr& channel)> fn) {
  106. std::lock_guard<std::mutex> locker(mutex_);
  107. for (auto& pair : channels) {
  108. fn(pair.second);
  109. }
  110. return channels.size();
  111. }
  112. // broadcast thread-safe
  113. int broadcast(const void* data, int size) {
  114. return foreachChannel([data, size](const TSocketChannelPtr& channel) {
  115. channel->write(data, size);
  116. });
  117. }
  118. int broadcast(const std::string& str) {
  119. return broadcast(str.data(), str.size());
  120. }
  121. private:
  122. static void newConnEvent(hio_t* connio) {
  123. TcpServerTmpl* server = (TcpServerTmpl*)hevent_userdata(connio);
  124. if (server->connectionNum() >= server->max_connections) {
  125. hlogw("over max_connections");
  126. hio_close(connio);
  127. return;
  128. }
  129. // NOTE: attach to worker loop
  130. EventLoop* worker_loop = currentThreadEventLoop;
  131. assert(worker_loop != NULL);
  132. hio_attach(worker_loop->loop(), connio);
  133. const TSocketChannelPtr& channel = server->addChannel(connio);
  134. channel->status = SocketChannel::CONNECTED;
  135. channel->onread = [server, &channel](Buffer* buf) {
  136. if (server->onMessage) {
  137. server->onMessage(channel, buf);
  138. }
  139. };
  140. channel->onwrite = [server, &channel](Buffer* buf) {
  141. if (server->onWriteComplete) {
  142. server->onWriteComplete(channel, buf);
  143. }
  144. };
  145. channel->onclose = [server, &channel]() {
  146. channel->status = SocketChannel::CLOSED;
  147. if (server->onConnection) {
  148. server->onConnection(channel);
  149. }
  150. server->removeChannel(channel);
  151. // NOTE: After removeChannel, channel may be destroyed,
  152. // so in this lambda function, no code should be added below.
  153. };
  154. if (server->unpack_setting.mode != UNPACK_MODE_NONE) {
  155. channel->setUnpack(&server->unpack_setting);
  156. }
  157. channel->startRead();
  158. if (server->onConnection) {
  159. server->onConnection(channel);
  160. }
  161. }
  162. static void onAccept(hio_t* connio) {
  163. TcpServerTmpl* server = (TcpServerTmpl*)hevent_userdata(connio);
  164. // NOTE: detach from acceptor loop
  165. hio_detach(connio);
  166. // Load Banlance: Round-Robin
  167. EventLoopPtr worker_loop = server->worker_threads.nextLoop();
  168. if (worker_loop == NULL) {
  169. worker_loop = server->acceptor_thread.loop();
  170. }
  171. worker_loop->runInLoop(std::bind(&TcpServerTmpl::newConnEvent, connio));
  172. }
  173. public:
  174. int listenfd;
  175. bool tls;
  176. unpack_setting_t unpack_setting;
  177. // Callback
  178. std::function<void(const TSocketChannelPtr&)> onConnection;
  179. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  180. // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written.
  181. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  182. uint32_t max_connections;
  183. private:
  184. // id => TSocketChannelPtr
  185. std::map<uint32_t, TSocketChannelPtr> channels; // GUAREDE_BY(mutex_)
  186. std::mutex mutex_;
  187. EventLoopThread acceptor_thread;
  188. EventLoopThreadPool worker_threads;
  189. };
  190. typedef TcpServerTmpl<SocketChannel> TcpServer;
  191. }
  192. #endif // HV_TCP_SERVER_HPP_