UdpClient_test.cpp 1004 B

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