UdpClient_test.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 remote_port [remote_host]\n", argv[0]);
  16. return -10;
  17. }
  18. int remote_port = atoi(argv[1]);
  19. const char* remote_host = "127.0.0.1";
  20. if (argc > 2) {
  21. remote_host = argv[2];
  22. }
  23. UdpClient cli;
  24. int sockfd = cli.createsocket(remote_port, remote_host);
  25. if (sockfd < 0) {
  26. return -20;
  27. }
  28. printf("client sendto port %d, sockfd=%d ...\n", remote_port, sockfd);
  29. cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  30. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  31. };
  32. cli.start();
  33. // sendto(time) every 3s
  34. cli.loop()->setInterval(3000, [&cli](TimerID timerID) {
  35. char str[DATETIME_FMT_BUFLEN] = {0};
  36. datetime_t dt = datetime_now();
  37. datetime_fmt(&dt, str);
  38. cli.sendto(str);
  39. });
  40. std::string str;
  41. while (std::getline(std::cin, str)) {
  42. if (str == "close") {
  43. cli.closesocket();
  44. } else if (str == "start") {
  45. cli.start();
  46. } else if (str == "stop") {
  47. cli.stop();
  48. break;
  49. } else {
  50. cli.sendto(str);
  51. }
  52. }
  53. return 0;
  54. }