UdpClient_test.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 <iostream>
  10. #include "UdpClient.h"
  11. #include "htime.h"
  12. using namespace hv;
  13. int main(int argc, char* argv[]) {
  14. if (argc < 2) {
  15. printf("Usage: %s port\n", argv[0]);
  16. return -10;
  17. }
  18. int port = atoi(argv[1]);
  19. UdpClient cli;
  20. int sockfd = cli.createsocket(port);
  21. if (sockfd < 0) {
  22. return -20;
  23. }
  24. printf("client sendto port %d, sockfd=%d ...\n", port, sockfd);
  25. cli.onMessage = [](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. std::string str;
  37. while (std::getline(std::cin, str)) {
  38. if (str == "close") {
  39. cli.closesocket();
  40. } else if (str == "start") {
  41. cli.start();
  42. } else if (str == "stop") {
  43. cli.stop();
  44. break;
  45. } else {
  46. cli.sendto(str);
  47. }
  48. }
  49. return 0;
  50. }