1
0

TcpServer.h 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. void setThreadNum(int num) {
  40. worker_threads.setThreadNum(num);
  41. }
  42. int startAccept() {
  43. assert(listenfd >= 0);
  44. hio_t* listenio = haccept(acceptor_thread.hloop(), listenfd, onAccept);
  45. hevent_set_userdata(listenio, this);
  46. if (tls) {
  47. hio_enable_ssl(listenio);
  48. }
  49. return 0;
  50. }
  51. void start(bool wait_threads_started = true) {
  52. worker_threads.start(wait_threads_started);
  53. acceptor_thread.start(wait_threads_started, std::bind(&TcpServerTmpl::startAccept, this));
  54. }
  55. // stop thread-safe
  56. void stop(bool wait_threads_stopped = true) {
  57. acceptor_thread.stop(wait_threads_stopped);
  58. worker_threads.stop(wait_threads_stopped);
  59. }
  60. int withTLS(const char* cert_file, const char* key_file) {
  61. if (cert_file) {
  62. hssl_ctx_init_param_t param;
  63. memset(&param, 0, sizeof(param));
  64. param.crt_file = cert_file;
  65. param.key_file = key_file;
  66. param.endpoint = HSSL_SERVER;
  67. if (hssl_ctx_init(&param) == NULL) {
  68. fprintf(stderr, "hssl_ctx_init failed!\n");
  69. return -1;
  70. }
  71. }
  72. tls = true;
  73. return 0;
  74. }
  75. void setUnpack(unpack_setting_t* setting) {
  76. if (setting) {
  77. enable_unpack = true;
  78. unpack_setting = *setting;
  79. } else {
  80. enable_unpack = false;
  81. }
  82. }
  83. // channel
  84. const TSocketChannelPtr& addChannel(hio_t* io) {
  85. int fd = hio_fd(io);
  86. auto channel = TSocketChannelPtr(new TSocketChannel(io));
  87. std::lock_guard<std::mutex> locker(mutex_);
  88. channels[fd] = channel;
  89. return channels[fd];
  90. }
  91. void removeChannel(const TSocketChannelPtr& channel) {
  92. int fd = channel->fd();
  93. std::lock_guard<std::mutex> locker(mutex_);
  94. channels.erase(fd);
  95. }
  96. size_t connectionNum() {
  97. std::lock_guard<std::mutex> locker(mutex_);
  98. return channels.size();
  99. }
  100. int foreachChannel(std::function<void(const TSocketChannelPtr& channel)> fn) {
  101. std::lock_guard<std::mutex> locker(mutex_);
  102. for (auto& pair : channels) {
  103. fn(pair.second);
  104. }
  105. return channels.size();
  106. }
  107. // broadcast thread-safe
  108. int broadcast(const void* data, int size) {
  109. return foreachChannel([data, size](const TSocketChannelPtr& channel) {
  110. channel->write(data, size);
  111. });
  112. }
  113. int broadcast(const std::string& str) {
  114. return broadcast(str.data(), str.size());
  115. }
  116. private:
  117. static void newConnEvent(hio_t* connio) {
  118. TcpServerTmpl* server = (TcpServerTmpl*)hevent_userdata(connio);
  119. if (server->connectionNum() >= server->max_connections) {
  120. hlogw("over max_connections");
  121. hio_close(connio);
  122. return;
  123. }
  124. // NOTE: attach to worker loop
  125. EventLoop* worker_loop = currentThreadEventLoop;
  126. assert(worker_loop != NULL);
  127. hio_attach(worker_loop->loop(), connio);
  128. const TSocketChannelPtr& channel = server->addChannel(connio);
  129. channel->status = SocketChannel::CONNECTED;
  130. channel->onread = [server, &channel](Buffer* buf) {
  131. if (server->onMessage) {
  132. server->onMessage(channel, buf);
  133. }
  134. };
  135. channel->onwrite = [server, &channel](Buffer* buf) {
  136. if (server->onWriteComplete) {
  137. server->onWriteComplete(channel, buf);
  138. }
  139. };
  140. channel->onclose = [server, &channel]() {
  141. channel->status = SocketChannel::CLOSED;
  142. if (server->onConnection) {
  143. server->onConnection(channel);
  144. }
  145. server->removeChannel(channel);
  146. // NOTE: After removeChannel, channel may be destroyed,
  147. // so in this lambda function, no code should be added below.
  148. };
  149. if (server->enable_unpack) {
  150. channel->setUnpack(&server->unpack_setting);
  151. }
  152. channel->startRead();
  153. if (server->onConnection) {
  154. server->onConnection(channel);
  155. }
  156. }
  157. static void onAccept(hio_t* connio) {
  158. TcpServerTmpl* server = (TcpServerTmpl*)hevent_userdata(connio);
  159. // NOTE: detach from acceptor loop
  160. hio_detach(connio);
  161. // Load Banlance: Round-Robin
  162. EventLoopPtr worker_loop = server->worker_threads.nextLoop();
  163. worker_loop->queueInLoop(std::bind(&TcpServerTmpl::newConnEvent, connio));
  164. }
  165. public:
  166. int listenfd;
  167. bool tls;
  168. bool enable_unpack;
  169. unpack_setting_t unpack_setting;
  170. // Callback
  171. std::function<void(const TSocketChannelPtr&)> onConnection;
  172. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  173. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  174. uint32_t max_connections;
  175. private:
  176. // fd => TSocketChannelPtr
  177. std::map<int, TSocketChannelPtr> channels; // GUAREDE_BY(mutex_)
  178. std::mutex mutex_;
  179. EventLoopThread acceptor_thread;
  180. EventLoopThreadPool worker_threads;
  181. };
  182. typedef TcpServerTmpl<SocketChannel> TcpServer;
  183. }
  184. #endif // HV_TCP_SERVER_HPP_