TcpServer_test.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * TcpServer_test.cpp
  3. *
  4. * @build: make evpp
  5. *
  6. */
  7. #include "TcpServer.h"
  8. using namespace hv;
  9. int main(int argc, char* argv[]) {
  10. if (argc < 2) {
  11. printf("Usage: %s port\n", argv[0]);
  12. return -10;
  13. }
  14. int port = atoi(argv[1]);
  15. hlog_set_level(LOG_LEVEL_DEBUG);
  16. TcpServer srv;
  17. int listenfd = srv.createsocket(port);
  18. if (listenfd < 0) {
  19. return -20;
  20. }
  21. printf("server listen on port %d, listenfd=%d ...\n", port, listenfd);
  22. srv.onConnection = [](const SocketChannelPtr& channel) {
  23. std::string peeraddr = channel->peeraddr();
  24. if (channel->isConnected()) {
  25. printf("%s connected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
  26. } else {
  27. printf("%s disconnected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid());
  28. }
  29. };
  30. srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  31. // echo
  32. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  33. channel->write(buf);
  34. };
  35. srv.setThreadNum(4);
  36. srv.start();
  37. // press Enter to stop
  38. while (getchar() != '\n');
  39. return 0;
  40. }