TcpServer_test.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 "TcpServer.h"
  10. using namespace hv;
  11. #define TEST_TLS 0
  12. int main(int argc, char* argv[]) {
  13. if (argc < 2) {
  14. printf("Usage: %s port\n", argv[0]);
  15. return -10;
  16. }
  17. int port = atoi(argv[1]);
  18. hlog_set_level(LOG_LEVEL_DEBUG);
  19. TcpServer srv;
  20. int listenfd = srv.createsocket(port);
  21. if (listenfd < 0) {
  22. return -20;
  23. }
  24. printf("server listen on port %d, listenfd=%d ...\n", port, listenfd);
  25. srv.onConnection = [](const SocketChannelPtr& channel) {
  26. std::string peeraddr = channel->peeraddr();
  27. if (channel->isConnected()) {
  28. printf("%s connected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
  29. } else {
  30. printf("%s disconnected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
  31. }
  32. };
  33. srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  34. // echo
  35. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  36. channel->write(buf);
  37. };
  38. srv.setThreadNum(4);
  39. srv.setLoadBalance(LB_LeastConnections);
  40. #if TEST_TLS
  41. hssl_ctx_opt_t ssl_opt;
  42. memset(&ssl_opt, 0, sizeof(hssl_ctx_opt_t));
  43. ssl_opt.crt_file = "cert/server.crt";
  44. ssl_opt.key_file = "cert/server.key";
  45. ssl_opt.verify_peer = 0;
  46. srv.withTLS(&ssl_opt);
  47. #endif
  48. srv.start();
  49. // press Enter to stop
  50. while (getchar() != '\n');
  51. return 0;
  52. }