TcpServer.h 6.2 KB

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