TcpServer.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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(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. unpack_setting = *setting;
  83. } else {
  84. unpack_setting.mode = UNPACK_MODE_NONE;
  85. }
  86. }
  87. // channel
  88. const TSocketChannelPtr& addChannel(hio_t* io) {
  89. uint32_t id = hio_id(io);
  90. auto channel = TSocketChannelPtr(new TSocketChannel(io));
  91. std::lock_guard<std::mutex> locker(mutex_);
  92. channels[id] = channel;
  93. return channels[id];
  94. }
  95. TSocketChannelPtr getChannelById(uint32_t id) {
  96. std::lock_guard<std::mutex> locker(mutex_);
  97. auto iter = channels.find(id);
  98. return iter != channels.end() ? iter->second : NULL;
  99. }
  100. void removeChannel(const TSocketChannelPtr& channel) {
  101. uint32_t id = channel->id();
  102. std::lock_guard<std::mutex> locker(mutex_);
  103. channels.erase(id);
  104. }
  105. size_t connectionNum() {
  106. std::lock_guard<std::mutex> locker(mutex_);
  107. return channels.size();
  108. }
  109. int foreachChannel(std::function<void(const TSocketChannelPtr& channel)> fn) {
  110. std::lock_guard<std::mutex> locker(mutex_);
  111. for (auto& pair : channels) {
  112. fn(pair.second);
  113. }
  114. return channels.size();
  115. }
  116. // broadcast thread-safe
  117. int broadcast(const void* data, int size) {
  118. return foreachChannel([data, size](const TSocketChannelPtr& channel) {
  119. channel->write(data, size);
  120. });
  121. }
  122. int broadcast(const std::string& str) {
  123. return broadcast(str.data(), str.size());
  124. }
  125. private:
  126. static void newConnEvent(hio_t* connio) {
  127. TcpServerTmpl* server = (TcpServerTmpl*)hevent_userdata(connio);
  128. if (server->connectionNum() >= server->max_connections) {
  129. hlogw("over max_connections");
  130. hio_close(connio);
  131. return;
  132. }
  133. // NOTE: attach to worker loop
  134. EventLoop* worker_loop = currentThreadEventLoop;
  135. assert(worker_loop != NULL);
  136. hio_attach(worker_loop->loop(), connio);
  137. const TSocketChannelPtr& channel = server->addChannel(connio);
  138. channel->status = SocketChannel::CONNECTED;
  139. channel->onread = [server, &channel](Buffer* buf) {
  140. if (server->onMessage) {
  141. server->onMessage(channel, buf);
  142. }
  143. };
  144. channel->onwrite = [server, &channel](Buffer* buf) {
  145. if (server->onWriteComplete) {
  146. server->onWriteComplete(channel, buf);
  147. }
  148. };
  149. channel->onclose = [server, &channel]() {
  150. channel->status = SocketChannel::CLOSED;
  151. if (server->onConnection) {
  152. server->onConnection(channel);
  153. }
  154. server->removeChannel(channel);
  155. // NOTE: After removeChannel, channel may be destroyed,
  156. // so in this lambda function, no code should be added below.
  157. };
  158. if (server->unpack_setting.mode != UNPACK_MODE_NONE) {
  159. channel->setUnpack(&server->unpack_setting);
  160. }
  161. channel->startRead();
  162. if (server->onConnection) {
  163. server->onConnection(channel);
  164. }
  165. }
  166. static void onAccept(hio_t* connio) {
  167. TcpServerTmpl* server = (TcpServerTmpl*)hevent_userdata(connio);
  168. // NOTE: detach from acceptor loop
  169. hio_detach(connio);
  170. // Load Banlance: Round-Robin
  171. EventLoopPtr worker_loop = server->worker_threads.nextLoop();
  172. if (worker_loop == NULL) {
  173. worker_loop = server->acceptor_thread.loop();
  174. }
  175. worker_loop->runInLoop(std::bind(&TcpServerTmpl::newConnEvent, connio));
  176. }
  177. public:
  178. int listenfd;
  179. bool tls;
  180. unpack_setting_t unpack_setting;
  181. // Callback
  182. std::function<void(const TSocketChannelPtr&)> onConnection;
  183. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  184. // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written.
  185. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  186. uint32_t max_connections;
  187. private:
  188. // id => TSocketChannelPtr
  189. std::map<uint32_t, TSocketChannelPtr> channels; // GUAREDE_BY(mutex_)
  190. std::mutex mutex_;
  191. EventLoopThread acceptor_thread;
  192. EventLoopThreadPool worker_threads;
  193. };
  194. typedef TcpServerTmpl<SocketChannel> TcpServer;
  195. }
  196. #endif // HV_TCP_SERVER_HPP_