UdpClient.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. hio_set_localaddr(channel->io(), &local_addr.sa, SOCKADDR_LEN(&local_addr));
  55. return ret;
  56. }
  57. // closesocket thread-safe
  58. void closesocket() {
  59. if (channel) {
  60. channel->close(true);
  61. }
  62. }
  63. int startRecv() {
  64. if (channel == NULL || channel->isClosed()) {
  65. int sockfd = createsocket(remote_port, remote_host.c_str());
  66. if (sockfd < 0) {
  67. hloge("createsocket %s:%d return %d!\n", remote_host.c_str(), remote_port, sockfd);
  68. return sockfd;
  69. }
  70. }
  71. if (channel == NULL || channel->isClosed()) {
  72. return -1;
  73. }
  74. channel->onread = [this](Buffer* buf) {
  75. if (onMessage) {
  76. onMessage(channel, buf);
  77. }
  78. };
  79. channel->onwrite = [this](Buffer* buf) {
  80. if (onWriteComplete) {
  81. onWriteComplete(channel, buf);
  82. }
  83. };
  84. #if WITH_KCP
  85. if (kcp_setting) {
  86. hio_set_kcp(channel->io(), kcp_setting);
  87. }
  88. #endif
  89. return channel->startRead();
  90. }
  91. int stopRecv() {
  92. if (channel == NULL) return -1;
  93. return channel->stopRead();
  94. }
  95. // start thread-safe
  96. void start() {
  97. loop_->runInLoop(std::bind(&UdpClientEventLoopTmpl::startRecv, this));
  98. }
  99. // sendto thread-safe
  100. int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL) {
  101. if (channel == NULL) return -1;
  102. std::lock_guard<std::mutex> locker(sendto_mutex);
  103. if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr));
  104. return channel->write(data, size);
  105. }
  106. int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL) {
  107. return sendto(buf->data(), buf->size(), peeraddr);
  108. }
  109. int sendto(const std::string& str, struct sockaddr* peeraddr = NULL) {
  110. return sendto(str.data(), str.size(), peeraddr);
  111. }
  112. #if WITH_KCP
  113. void setKcp(kcp_setting_t* setting) {
  114. if (setting == NULL) {
  115. HV_FREE(kcp_setting);
  116. return;
  117. }
  118. if (kcp_setting == NULL) {
  119. HV_ALLOC_SIZEOF(kcp_setting);
  120. }
  121. *kcp_setting = *setting;
  122. }
  123. #endif
  124. public:
  125. TSocketChannelPtr channel;
  126. std::string remote_host;
  127. int remote_port;
  128. #if WITH_KCP
  129. kcp_setting_t* kcp_setting;
  130. #endif
  131. // Callback
  132. std::function<void(const TSocketChannelPtr&, Buffer*)> onMessage;
  133. // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written.
  134. std::function<void(const TSocketChannelPtr&, Buffer*)> onWriteComplete;
  135. private:
  136. std::mutex sendto_mutex;
  137. EventLoopPtr loop_;
  138. };
  139. template<class TSocketChannel = SocketChannel>
  140. class UdpClientTmpl : private EventLoopThread, public UdpClientEventLoopTmpl<TSocketChannel> {
  141. public:
  142. UdpClientTmpl(EventLoopPtr loop = NULL)
  143. : EventLoopThread(loop)
  144. , UdpClientEventLoopTmpl<TSocketChannel>(EventLoopThread::loop())
  145. , is_loop_owner(loop == NULL)
  146. {}
  147. virtual ~UdpClientTmpl() {
  148. stop(true);
  149. }
  150. const EventLoopPtr& loop() {
  151. return EventLoopThread::loop();
  152. }
  153. // start thread-safe
  154. void start(bool wait_threads_started = true) {
  155. if (isRunning()) {
  156. UdpClientEventLoopTmpl<TSocketChannel>::start();
  157. } else {
  158. EventLoopThread::start(wait_threads_started, std::bind(&UdpClientTmpl::startRecv, this));
  159. }
  160. }
  161. // stop thread-safe
  162. void stop(bool wait_threads_stopped = true) {
  163. UdpClientEventLoopTmpl<TSocketChannel>::closesocket();
  164. if (is_loop_owner) {
  165. EventLoopThread::stop(wait_threads_stopped);
  166. }
  167. }
  168. private:
  169. bool is_loop_owner;
  170. };
  171. typedef UdpClientTmpl<SocketChannel> UdpClient;
  172. }
  173. #endif // HV_UDP_CLIENT_HPP_