UdpServer.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. }
  12. virtual ~UdpServer() {
  13. }
  14. const EventLoopPtr& loop() {
  15. return loop_thread.loop();
  16. }
  17. //@retval >=0 bindfd, <0 error
  18. int createsocket(int port, const char* host = "0.0.0.0") {
  19. hio_t* io = hloop_create_udp_server(loop_thread.hloop(), host, port);
  20. if (io == NULL) return -1;
  21. channel.reset(new SocketChannel(io));
  22. return channel->fd();
  23. }
  24. void start(bool wait_threads_started = true) {
  25. loop_thread.start(wait_threads_started,
  26. [this]() {
  27. assert(channel != NULL);
  28. channel->onread = [this](Buffer* buf) {
  29. if (onMessage) {
  30. onMessage(channel, buf);
  31. }
  32. };
  33. channel->onwrite = [this](Buffer* buf) {
  34. if (onWriteComplete) {
  35. onWriteComplete(channel, buf);
  36. }
  37. };
  38. channel->startRead();
  39. return 0;
  40. }
  41. );
  42. }
  43. void stop(bool wait_threads_stopped = true) {
  44. loop_thread.stop(wait_threads_stopped);
  45. }
  46. int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL) {
  47. if (channel == NULL) return 0;
  48. if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr));
  49. return channel->write(buf);
  50. }
  51. int sendto(const std::string& str, struct sockaddr* peeraddr = NULL) {
  52. if (channel == NULL) return 0;
  53. if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr));
  54. return channel->write(str);
  55. }
  56. public:
  57. SocketChannelPtr channel;
  58. // Callback
  59. MessageCallback onMessage;
  60. WriteCompleteCallback onWriteComplete;
  61. private:
  62. EventLoopThread loop_thread;
  63. };
  64. }
  65. #endif // HV_UDP_SERVER_HPP_