UdpClient.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 start(bool wait_threads_started = true) {
  25. loop_thread.start(wait_threads_started,
  26. [this]() {
  27. assert(channel != NULL);
  28. channel->onread = [this](Buffer* buf) {
  29. if (onMessage) {
  30. onMessage(channel, buf);
  31. }
  32. };
  33. channel->onwrite = [this](Buffer* buf) {
  34. if (onWriteComplete) {
  35. onWriteComplete(channel, buf);
  36. }
  37. };
  38. channel->startRead();
  39. return 0;
  40. }
  41. );
  42. }
  43. void stop(bool wait_threads_stopped = true) {
  44. loop_thread.stop(wait_threads_stopped);
  45. }
  46. int sendto(Buffer* buf) {
  47. if (channel == NULL) return 0;
  48. return channel->write(buf);
  49. }
  50. int sendto(const std::string& str) {
  51. if (channel == NULL) return 0;
  52. return channel->write(str);
  53. }
  54. public:
  55. SocketChannelPtr channel;
  56. // Callback
  57. MessageCallback onMessage;
  58. WriteCompleteCallback onWriteComplete;
  59. private:
  60. EventLoopThread loop_thread;
  61. };
  62. }
  63. #endif // HV_UDP_CLIENT_HPP_