UdpClient.h 5.5 KB

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