1
0

UdpServer.h 2.5 KB

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