TcpServer.h 5.9 KB

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