TcpServer.h 5.2 KB

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