TcpServer_test.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * TcpServer_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 "TcpServer.h"
  11. using namespace hv;
  12. #define TEST_TLS 0
  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. hlog_set_level(LOG_LEVEL_DEBUG);
  20. TcpServer srv;
  21. int listenfd = srv.createsocket(port);
  22. if (listenfd < 0) {
  23. return -20;
  24. }
  25. printf("server listen on port %d, listenfd=%d ...\n", port, listenfd);
  26. srv.onConnection = [](const SocketChannelPtr& channel) {
  27. std::string peeraddr = channel->peeraddr();
  28. if (channel->isConnected()) {
  29. printf("%s connected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
  30. } else {
  31. printf("%s disconnected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
  32. }
  33. };
  34. srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  35. // echo
  36. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  37. channel->write(buf);
  38. };
  39. srv.setThreadNum(4);
  40. srv.setLoadBalance(LB_LeastConnections);
  41. #if TEST_TLS
  42. hssl_ctx_opt_t ssl_opt;
  43. memset(&ssl_opt, 0, sizeof(hssl_ctx_opt_t));
  44. ssl_opt.crt_file = "cert/server.crt";
  45. ssl_opt.key_file = "cert/server.key";
  46. ssl_opt.verify_peer = 0;
  47. srv.withTLS(&ssl_opt);
  48. #endif
  49. srv.start();
  50. std::string str;
  51. while (std::getline(std::cin, str)) {
  52. if (str == "close") {
  53. srv.closesocket();
  54. } else if (str == "start") {
  55. srv.start();
  56. } else if (str == "stop") {
  57. srv.stop();
  58. break;
  59. } else {
  60. srv.broadcast(str.data(), str.size());
  61. }
  62. }
  63. return 0;
  64. }