TcpClient_test.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * TcpClient_test.cpp
  3. *
  4. * @build make evpp
  5. * @server bin/TcpServer_test 1234
  6. * @client bin/TcpClient_test 1234
  7. *
  8. */
  9. #include <iostream>
  10. #include "TcpClient.h"
  11. #include "htime.h"
  12. #define TEST_RECONNECT 1
  13. #define TEST_TLS 0
  14. using namespace hv;
  15. int main(int argc, char* argv[]) {
  16. if (argc < 2) {
  17. printf("Usage: %s remote_port [remote_host]\n", argv[0]);
  18. return -10;
  19. }
  20. int remote_port = atoi(argv[1]);
  21. const char* remote_host = "127.0.0.1";
  22. if (argc > 2) {
  23. remote_host = argv[2];
  24. }
  25. TcpClient cli;
  26. int connfd = cli.createsocket(remote_port, remote_host);
  27. if (connfd < 0) {
  28. return -20;
  29. }
  30. printf("client connect to port %d, connfd=%d ...\n", remote_port, connfd);
  31. cli.onConnection = [&cli](const SocketChannelPtr& channel) {
  32. std::string peeraddr = channel->peeraddr();
  33. if (channel->isConnected()) {
  34. printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
  35. // send(time) every 3s
  36. setInterval(3000, [channel](TimerID timerID){
  37. if (channel->isConnected()) {
  38. if (channel->isWriteComplete()) {
  39. char str[DATETIME_FMT_BUFLEN] = {0};
  40. datetime_t dt = datetime_now();
  41. datetime_fmt(&dt, str);
  42. channel->write(str);
  43. }
  44. } else {
  45. killTimer(timerID);
  46. }
  47. });
  48. } else {
  49. printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
  50. }
  51. if (cli.isReconnect()) {
  52. printf("reconnect cnt=%d, delay=%d\n", cli.reconn_setting->cur_retry_cnt, cli.reconn_setting->cur_delay);
  53. }
  54. };
  55. cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  56. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  57. };
  58. #if TEST_RECONNECT
  59. // reconnect: 1,2,4,8,10,10,10...
  60. reconn_setting_t reconn;
  61. reconn_setting_init(&reconn);
  62. reconn.min_delay = 1000;
  63. reconn.max_delay = 10000;
  64. reconn.delay_policy = 2;
  65. cli.setReconnect(&reconn);
  66. #endif
  67. #if TEST_TLS
  68. cli.withTLS();
  69. #endif
  70. cli.start();
  71. std::string str;
  72. while (std::getline(std::cin, str)) {
  73. if (str == "close") {
  74. cli.closesocket();
  75. } else if (str == "start") {
  76. cli.start();
  77. } else if (str == "stop") {
  78. cli.stop();
  79. break;
  80. } else {
  81. if (!cli.isConnected()) break;
  82. cli.send(str);
  83. }
  84. }
  85. return 0;
  86. }