1
0

UdpServer.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #ifndef HV_UDP_SERVER_HPP_
  2. #define HV_UDP_SERVER_HPP_
  3. #include "hsocket.h"
  4. #include "EventLoopThreadPool.h"
  5. #include "Channel.h"
  6. namespace hv {
  7. template<class TSocketChannel = SocketChannel>
  8. class UdpServerTmpl {
  9. public:
  10. typedef std::shared_ptr<TSocketChannel> TSocketChannelPtr;
  11. UdpServerTmpl() {
  12. #if WITH_KCP
  13. enable_kcp = false;
  14. #endif
  15. }
  16. virtual ~UdpServerTmpl() {
  17. }
  18. const EventLoopPtr& loop() {
  19. return loop_thread.loop();
  20. }
  21. //@retval >=0 bindfd, <0 error
  22. int createsocket(int port, const char* host = "0.0.0.0") {
  23. hio_t* io = hloop_create_udp_server(loop_thread.hloop(), host, port);
  24. if (io == NULL) return -1;
  25. channel.reset(new TSocketChannel(io));
  26. return channel->fd();
  27. }
  28. void closesocket() {
  29. if (channel) {
  30. channel->close();
  31. channel = NULL;
  32. }
  33. }
  34. int startRecv() {
  35. assert(channel != NULL);
  36. channel->onread = [this](Buffer* buf) {
  37. if (onMessage) {
  38. onMessage(channel, buf);
  39. }
  40. };
  41. channel->onwrite = [this](Buffer* buf) {
  42. if (onWriteComplete) {
  43. onWriteComplete(channel, buf);
  44. }
  45. };
  46. #if WITH_KCP
  47. if (enable_kcp) {
  48. hio_set_kcp(channel->io(), &kcp_setting);
  49. }
  50. #endif
  51. return channel->startRead();
  52. }
  53. void start(bool wait_threads_started = true) {
  54. loop_thread.start(wait_threads_started, std::bind(&UdpServerTmpl::startRecv, this));
  55. }
  56. void stop(bool wait_threads_stopped = true) {
  57. loop_thread.stop(wait_threads_stopped);
  58. }
  59. int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL) {
  60. if (channel == NULL) return -1;
  61. std::lock_guard<std::mutex> locker(sendto_mutex);
  62. if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr));
  63. return channel->write(data, size);
  64. }
  65. int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL) {
  66. return sendto(buf->data(), buf->size(), peeraddr);
  67. }
  68. int sendto(const std::string& str, struct sockaddr* peeraddr = NULL) {
  69. return sendto(str.data(), str.size(), peeraddr);
  70. }
  71. public:
  72. TSocketChannelPtr channel;
  73. #if WITH_KCP
  74. bool enable_kcp;
  75. kcp_setting_t kcp_setting;
  76. #endif
  77. // Callback
  78. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  79. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  80. private:
  81. std::mutex sendto_mutex;
  82. EventLoopThread loop_thread;
  83. };
  84. typedef UdpServerTmpl<SocketChannel> UdpServer;
  85. }
  86. #endif // HV_UDP_SERVER_HPP_