1
0

TcpClient_test.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 "TcpClient.h"
  10. #include "htime.h"
  11. #define TEST_RECONNECT 1
  12. #define TEST_TLS 0
  13. using namespace hv;
  14. int main(int argc, char* argv[]) {
  15. if (argc < 2) {
  16. printf("Usage: %s port\n", argv[0]);
  17. return -10;
  18. }
  19. int port = atoi(argv[1]);
  20. TcpClient cli;
  21. int connfd = cli.createsocket(port);
  22. if (connfd < 0) {
  23. return -20;
  24. }
  25. printf("client connect to port %d, connfd=%d ...\n", port, connfd);
  26. cli.onConnection = [&cli](const SocketChannelPtr& channel) {
  27. std::string peeraddr = channel->peeraddr();
  28. if (channel->isConnected()) {
  29. printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
  30. // send(time) every 3s
  31. setInterval(3000, [channel](TimerID timerID){
  32. if (channel->isConnected()) {
  33. if (channel->isWriteComplete()) {
  34. char str[DATETIME_FMT_BUFLEN] = {0};
  35. datetime_t dt = datetime_now();
  36. datetime_fmt(&dt, str);
  37. channel->write(str);
  38. }
  39. } else {
  40. killTimer(timerID);
  41. }
  42. });
  43. } else {
  44. printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
  45. }
  46. if (cli.isReconnect()) {
  47. printf("reconnect cnt=%d, delay=%d\n", cli.reconn_setting->cur_retry_cnt, cli.reconn_setting->cur_delay);
  48. }
  49. };
  50. cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  51. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  52. };
  53. #if TEST_RECONNECT
  54. // reconnect: 1,2,4,8,10,10,10...
  55. reconn_setting_t reconn;
  56. reconn_setting_init(&reconn);
  57. reconn.min_delay = 1000;
  58. reconn.max_delay = 10000;
  59. reconn.delay_policy = 2;
  60. cli.setReconnect(&reconn);
  61. #endif
  62. #if TEST_TLS
  63. cli.withTLS();
  64. #endif
  65. cli.start();
  66. // press Enter to stop
  67. while (getchar() != '\n');
  68. return 0;
  69. }