1
0

UdpClient_test.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. * UdpClient_test.cpp
  3. *
  4. * @build
  5. * make libhv && sudo make install
  6. * g++ -std=c++11 UdpClient_test.cpp -o UdpClient_test -I/usr/local/include/hv -lhv -lpthread
  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.onWriteComplete = [](const SocketChannelPtr& channel, Buffer* buf) {
  28. printf("> %.*s\n", (int)buf->size(), (char*)buf->data());
  29. };
  30. cli.start();
  31. // sendto(time) every 3s
  32. cli.loop()->setInterval(3000, [&cli](TimerID timerID) {
  33. char str[DATETIME_FMT_BUFLEN] = {0};
  34. datetime_t dt = datetime_now();
  35. datetime_fmt(&dt, str);
  36. cli.sendto(str);
  37. });
  38. while (1) hv_sleep(1);
  39. return 0;
  40. }