UdpClient_test.cpp 931 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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.start();
  26. // sendto(time) every 3s
  27. cli.loop()->setInterval(3000, [&cli](TimerID timerID) {
  28. char str[DATETIME_FMT_BUFLEN] = {0};
  29. datetime_t dt = datetime_now();
  30. datetime_fmt(&dt, str);
  31. cli.sendto(str);
  32. });
  33. // press Enter to stop
  34. while (getchar() != '\n');
  35. return 0;
  36. }