Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

test_tcpEchoServer.cpp 2.1KB

6 månader sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <csignal>
  11. #include <iostream>
  12. #ifndef _WIN32
  13. #include <unistd.h>
  14. #endif
  15. #include "Util/logger.h"
  16. #include "Util/TimeTicker.h"
  17. #include "Network/TcpServer.h"
  18. #include "Network/Session.h"
  19. using namespace std;
  20. using namespace toolkit;
  21. class EchoSession: public Session {
  22. public:
  23. EchoSession(const Socket::Ptr &sock) :
  24. Session(sock) {
  25. DebugL;
  26. }
  27. ~EchoSession() {
  28. DebugL;
  29. }
  30. virtual void onRecv(const Buffer::Ptr &buf) override{
  31. //处理客户端发送过来的数据
  32. TraceL << buf->data() << " from port:" << get_local_port();
  33. send(buf);
  34. }
  35. virtual void onError(const SockException &err) override{
  36. //客户端断开连接或其他原因导致该对象脱离TCPServer管理
  37. WarnL << err.what();
  38. }
  39. virtual void onManager() override{
  40. //定时管理该对象,譬如会话超时检查
  41. DebugL;
  42. }
  43. private:
  44. Ticker _ticker;
  45. };
  46. int main() {
  47. //初始化日志模块
  48. Logger::Instance().add(std::make_shared<ConsoleChannel>());
  49. Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
  50. //加载证书,证书包含公钥和私钥
  51. SSL_Initor::Instance().loadCertificate((exeDir() + "ssl.p12").data());
  52. SSL_Initor::Instance().trustCertificate((exeDir() + "ssl.p12").data());
  53. SSL_Initor::Instance().ignoreInvalidCertificate(false);
  54. TcpServer::Ptr server(new TcpServer());
  55. server->start<EchoSession>(9000);//监听9000端口
  56. TcpServer::Ptr serverSSL(new TcpServer());
  57. serverSSL->start<SessionWithSSL<EchoSession> >(9001);//监听9001端口
  58. //退出程序事件处理
  59. static semaphore sem;
  60. signal(SIGINT, [](int) { sem.post(); });// 设置退出信号
  61. sem.wait();
  62. return 0;
  63. }