TcpServer.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. enable_unpack = false;
  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(const char* cert_file, const char* key_file) {
  66. if (cert_file) {
  67. hssl_ctx_init_param_t param;
  68. memset(&param, 0, sizeof(param));
  69. param.crt_file = cert_file;
  70. param.key_file = key_file;
  71. param.endpoint = HSSL_SERVER;
  72. if (hssl_ctx_init(&param) == NULL) {
  73. fprintf(stderr, "hssl_ctx_init failed!\n");
  74. return -1;
  75. }
  76. }
  77. tls = true;
  78. return 0;
  79. }
  80. void setUnpack(unpack_setting_t* setting) {
  81. if (setting) {
  82. enable_unpack = true;
  83. unpack_setting = *setting;
  84. } else {
  85. enable_unpack = false;
  86. }
  87. }
  88. // channel
  89. const TSocketChannelPtr& addChannel(hio_t* io) {
  90. int fd = hio_fd(io);
  91. auto channel = TSocketChannelPtr(new TSocketChannel(io));
  92. std::lock_guard<std::mutex> locker(mutex_);
  93. channels[fd] = channel;
  94. return channels[fd];
  95. }
  96. void removeChannel(const TSocketChannelPtr& channel) {
  97. int fd = channel->fd();
  98. std::lock_guard<std::mutex> locker(mutex_);
  99. channels.erase(fd);
  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->enable_unpack) {
  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. bool enable_unpack;
  177. unpack_setting_t unpack_setting;
  178. // Callback
  179. std::function<void(const TSocketChannelPtr&)> onConnection;
  180. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  181. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  182. uint32_t max_connections;
  183. private:
  184. // fd => TSocketChannelPtr
  185. std::map<int, 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_