You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.3KB

  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. #include "Util/logger.h"
  13. #include "Network/TcpClient.h"
  14. using namespace std;
  15. using namespace toolkit;
  16. class TestClient: public TcpClient {
  17. public:
  18. using Ptr = std::shared_ptr<TestClient>;
  19. TestClient():TcpClient() {
  20. DebugL;
  21. }
  22. ~TestClient(){
  23. DebugL;
  24. }
  25. protected:
  26. virtual void onConnect(const SockException &ex) override{
  27. //连接结果事件
  28. InfoL << (ex ? ex.what() : "success");
  29. }
  30. virtual void onRecv(const Buffer::Ptr &pBuf) override{
  31. //接收数据事件
  32. DebugL << pBuf->data() << " from port:" << get_peer_port();
  33. }
  34. virtual void onFlush() override{
  35. //发送阻塞后,缓存清空事件
  36. DebugL;
  37. }
  38. virtual void onErr(const SockException &ex) override{
  39. //断开连接事件,一般是EOF
  40. WarnL << ex.what();
  41. }
  42. virtual void onManager() override{
  43. //定时发送数据到服务器
  44. auto buf = BufferRaw::create();
  45. if(buf){
  46. buf->assign("[BufferRaw]\0");
  47. (*this) << _nTick++ << " "
  48. << 3.14 << " "
  49. << string("string") << " "
  50. <<(Buffer::Ptr &)buf;
  51. }
  52. }
  53. private:
  54. int _nTick = 0;
  55. };
  56. int main() {
  57. // 设置日志系统
  58. Logger::Instance().add(std::make_shared<ConsoleChannel>());
  59. Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
  60. TestClient::Ptr client(new TestClient());//必须使用智能指针
  61. client->startConnect("127.0.0.1",9000);//连接服务器
  62. TcpClientWithSSL<TestClient>::Ptr clientSSL(new TcpClientWithSSL<TestClient>());//必须使用智能指针
  63. clientSSL->startConnect("127.0.0.1",9001);//连接服务器
  64. //退出程序事件处理
  65. static semaphore sem;
  66. signal(SIGINT, [](int) { sem.post(); });// 设置退出信号
  67. sem.wait();
  68. return 0;
  69. }