UdpClient_test.cpp 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * UdpClient_test.cpp
  3. *
  4. * @build: make evpp
  5. *
  6. */
  7. #include "UdpClient.h"
  8. #include "htime.h"
  9. using namespace hv;
  10. int main(int argc, char* argv[]) {
  11. if (argc < 2) {
  12. printf("Usage: %s port\n", argv[0]);
  13. return -10;
  14. }
  15. int port = atoi(argv[1]);
  16. UdpClient cli;
  17. int sockfd = cli.createsocket(port);
  18. if (sockfd < 0) {
  19. return -20;
  20. }
  21. printf("client sendto port %d, sockfd=%d ...\n", port, sockfd);
  22. cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  23. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  24. };
  25. cli.onWriteComplete = [](const SocketChannelPtr& channel, Buffer* buf) {
  26. printf("> %.*s\n", (int)buf->size(), (char*)buf->data());
  27. };
  28. cli.start();
  29. // sendto(time) every 3s
  30. cli.loop()->setInterval(3000, [&cli](TimerID timerID) {
  31. char str[DATETIME_FMT_BUFLEN] = {0};
  32. datetime_t dt = datetime_now();
  33. datetime_fmt(&dt, str);
  34. cli.sendto(str);
  35. });
  36. while (1) hv_sleep(1);
  37. return 0;
  38. }