UdpClient.h 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #ifndef HV_UDP_CLIENT_HPP_
  2. #define HV_UDP_CLIENT_HPP_
  3. #include "hsocket.h"
  4. #include "EventLoopThread.h"
  5. #include "Callback.h"
  6. #include "Channel.h"
  7. namespace hv {
  8. class UdpClient {
  9. public:
  10. UdpClient() {
  11. #if WITH_KCP
  12. enable_kcp = false;
  13. #endif
  14. }
  15. virtual ~UdpClient() {
  16. }
  17. const EventLoopPtr& loop() {
  18. return loop_thread.loop();
  19. }
  20. //@retval >=0 sockfd, <0 error
  21. int createsocket(int port, const char* host = "127.0.0.1") {
  22. hio_t* io = hloop_create_udp_client(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(&UdpClient::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. #if WITH_KCP
  71. void setKcp(kcp_setting_t* setting) {
  72. if (setting) {
  73. enable_kcp = true;
  74. kcp_setting = *setting;
  75. } else {
  76. enable_kcp = false;
  77. }
  78. }
  79. #endif
  80. public:
  81. SocketChannelPtr channel;
  82. #if WITH_KCP
  83. bool enable_kcp;
  84. kcp_setting_t kcp_setting;
  85. #endif
  86. // Callback
  87. MessageCallback onMessage;
  88. WriteCompleteCallback onWriteComplete;
  89. private:
  90. std::mutex sendto_mutex;
  91. EventLoopThread loop_thread;
  92. };
  93. }
  94. #endif // HV_UDP_CLIENT_HPP_