UdpClient.h 2.1 KB

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