UdpClient.h 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #ifndef HV_UDP_CLIENT_HPP_
  2. #define HV_UDP_CLIENT_HPP_
  3. #include "hsocket.h"
  4. #include "EventLoopThread.h"
  5. #include "Channel.h"
  6. namespace hv {
  7. template<class TSocketChannel = SocketChannel>
  8. class UdpClientEventLoopTmpl {
  9. public:
  10. typedef std::shared_ptr<TSocketChannel> TSocketChannelPtr;
  11. UdpClientEventLoopTmpl(EventLoopPtr loop = NULL) {
  12. loop_ = loop ? loop : std::make_shared<EventLoop>();
  13. remote_port = 0;
  14. #if WITH_KCP
  15. kcp_setting = NULL;
  16. #endif
  17. }
  18. virtual ~UdpClientEventLoopTmpl() {
  19. #if WITH_KCP
  20. HV_FREE(kcp_setting);
  21. #endif
  22. }
  23. const EventLoopPtr& loop() {
  24. return loop_;
  25. }
  26. // NOTE: By default, not bind local port. If necessary, you can call bind() after createsocket().
  27. // @retval >=0 sockfd, <0 error
  28. int createsocket(int remote_port, const char* remote_host = "127.0.0.1") {
  29. hio_t* io = hloop_create_udp_client(loop_->loop(), remote_host, remote_port);
  30. if (io == NULL) return -1;
  31. this->remote_host = remote_host;
  32. this->remote_port = remote_port;
  33. channel = std::make_shared<TSocketChannel>(io);
  34. int sockfd = channel->fd();
  35. if (hv_strendswith(remote_host, ".255")) {
  36. udp_broadcast(sockfd, 1);
  37. }
  38. return sockfd;
  39. }
  40. int bind(int local_port, const char* local_host = "0.0.0.0") {
  41. if (channel == NULL || channel->isClosed()) {
  42. return -1;
  43. }
  44. sockaddr_u local_addr;
  45. memset(&local_addr, 0, sizeof(local_addr));
  46. int ret = sockaddr_set_ipport(&local_addr, local_host, local_port);
  47. if (ret != 0) {
  48. return NABS(ret);
  49. }
  50. ret = ::bind(channel->fd(), &local_addr.sa, SOCKADDR_LEN(&local_addr));
  51. if (ret != 0) {
  52. perror("bind");
  53. }
  54. return ret;
  55. }
  56. // closesocket thread-safe
  57. void closesocket() {
  58. if (channel) {
  59. channel->close(true);
  60. }
  61. }
  62. int startRecv() {
  63. if (channel == NULL || channel->isClosed()) {
  64. int sockfd = createsocket(remote_port, remote_host.c_str());
  65. if (sockfd < 0) {
  66. hloge("createsocket %s:%d return %d!\n", remote_host.c_str(), remote_port, sockfd);
  67. return sockfd;
  68. }
  69. }
  70. if (channel == NULL || channel->isClosed()) {
  71. return -1;
  72. }
  73. channel->onread = [this](Buffer* buf) {
  74. if (onMessage) {
  75. onMessage(channel, buf);
  76. }
  77. };
  78. channel->onwrite = [this](Buffer* buf) {
  79. if (onWriteComplete) {
  80. onWriteComplete(channel, buf);
  81. }
  82. };
  83. #if WITH_KCP
  84. if (kcp_setting) {
  85. hio_set_kcp(channel->io(), kcp_setting);
  86. }
  87. #endif
  88. return channel->startRead();
  89. }
  90. int stopRecv() {
  91. if (channel == NULL) return -1;
  92. return channel->stopRead();
  93. }
  94. // start thread-safe
  95. void start() {
  96. loop_->runInLoop(std::bind(&UdpClientEventLoopTmpl::startRecv, this));
  97. }
  98. // sendto thread-safe
  99. int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL) {
  100. if (channel == NULL) return -1;
  101. std::lock_guard<std::mutex> locker(sendto_mutex);
  102. if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr));
  103. return channel->write(data, size);
  104. }
  105. int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL) {
  106. return sendto(buf->data(), buf->size(), peeraddr);
  107. }
  108. int sendto(const std::string& str, struct sockaddr* peeraddr = NULL) {
  109. return sendto(str.data(), str.size(), peeraddr);
  110. }
  111. #if WITH_KCP
  112. void setKcp(kcp_setting_t* setting) {
  113. if (setting == NULL) {
  114. HV_FREE(kcp_setting);
  115. return;
  116. }
  117. if (kcp_setting == NULL) {
  118. HV_ALLOC_SIZEOF(kcp_setting);
  119. }
  120. *kcp_setting = *setting;
  121. }
  122. #endif
  123. public:
  124. TSocketChannelPtr channel;
  125. std::string remote_host;
  126. int remote_port;
  127. #if WITH_KCP
  128. kcp_setting_t* kcp_setting;
  129. #endif
  130. // Callback
  131. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  132. // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written.
  133. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  134. private:
  135. std::mutex sendto_mutex;
  136. EventLoopPtr loop_;
  137. };
  138. template<class TSocketChannel = SocketChannel>
  139. class UdpClientTmpl : private EventLoopThread, public UdpClientEventLoopTmpl<TSocketChannel> {
  140. public:
  141. UdpClientTmpl(EventLoopPtr loop = NULL)
  142. : EventLoopThread(loop)
  143. , UdpClientEventLoopTmpl<TSocketChannel>(EventLoopThread::loop())
  144. , is_loop_owner(loop == NULL)
  145. {}
  146. virtual ~UdpClientTmpl() {
  147. stop(true);
  148. }
  149. const EventLoopPtr& loop() {
  150. return EventLoopThread::loop();
  151. }
  152. // start thread-safe
  153. void start(bool wait_threads_started = true) {
  154. if (isRunning()) {
  155. UdpClientEventLoopTmpl<TSocketChannel>::start();
  156. } else {
  157. EventLoopThread::start(wait_threads_started, std::bind(&UdpClientTmpl::startRecv, this));
  158. }
  159. }
  160. // stop thread-safe
  161. void stop(bool wait_threads_stopped = true) {
  162. UdpClientEventLoopTmpl<TSocketChannel>::closesocket();
  163. if (is_loop_owner) {
  164. EventLoopThread::stop(wait_threads_stopped);
  165. }
  166. }
  167. private:
  168. bool is_loop_owner;
  169. };
  170. typedef UdpClientTmpl<SocketChannel> UdpClient;
  171. }
  172. #endif // HV_UDP_CLIENT_HPP_