1
0

TcpServer_test.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * TcpServer_test.cpp
  3. *
  4. * @build
  5. * make libhv && sudo make install
  6. * g++ -std=c++11 TcpServer_test.cpp -o TcpServer_test -I/usr/local/include/hv -lhv -lpthread
  7. *
  8. */
  9. #include "TcpServer.h"
  10. using namespace hv;
  11. int main(int argc, char* argv[]) {
  12. if (argc < 2) {
  13. printf("Usage: %s port\n", argv[0]);
  14. return -10;
  15. }
  16. int port = atoi(argv[1]);
  17. TcpServer srv;
  18. int listenfd = srv.createsocket(port);
  19. if (listenfd < 0) {
  20. return -20;
  21. }
  22. printf("server listen on port %d, listenfd=%d ...\n", port, listenfd);
  23. srv.onConnection = [](const SocketChannelPtr& channel) {
  24. std::string peeraddr = channel->peeraddr();
  25. if (channel->isConnected()) {
  26. printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd());
  27. } else {
  28. printf("%s disconnected! connfd=%d\n", peeraddr.c_str(), channel->fd());
  29. }
  30. };
  31. srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
  32. // echo
  33. printf("< %.*s\n", (int)buf->size(), (char*)buf->data());
  34. channel->write(buf);
  35. };
  36. srv.onWriteComplete = [](const SocketChannelPtr& channel, Buffer* buf) {
  37. printf("> %.*s\n", (int)buf->size(), (char*)buf->data());
  38. };
  39. srv.setThreadNum(4);
  40. srv.start();
  41. while (1) sleep(1);
  42. return 0;
  43. }