C++ ASIO 实现异步套接字管理

打印 上一主题 下一主题

主题 889|帖子 889|积分 2667

Boost ASIO(Asynchronous I/O)是一个用于异步I/O操作的C++库,该框架提供了一种方便的方式来处理网络通信、多线程编程和异步操作。特别适用于网络应用程序的开发,从基本的网络通信到复杂的异步操作,如远程控制程序、高并发服务器等都可以使用该框架。该框架的优势在于其允许处理多个并发连接,而不必创建一个线程来管理每个连接。最重要的是ASIO是一个跨平台库,可以运行在任何支持C++的平台下。

本章笔者将介绍如何通过ASIO框架实现一个简单的异步网络套接字应用程序,该程序支持对Socket套接字的存储,默认将套接字放入到一个Map容器内,当需要使用时只需要将套接字在容器内取出并实现通信,客户端下线时则自动从Map容器内移除,通过对本章知识的学习读者可以很容易的构建一个跨平台的简单远控功能。
AsyncTcpClient 异步客户端

如下这段代码实现了一个基本的带有自动心跳检测的客户端,它可以通过异步连接与服务器进行通信,并根据不同的命令返回不同的数据。代码逻辑较为简单,但为了保证可靠性和稳定性,实际应用中需要进一步优化、处理错误和异常情况,以及增加更多的功能和安全性措施。
首先我们封装实现AsyncConnect类,该类内主要实现两个功能,其中aysnc_connect()方法用于实现异步连接到服务端,而port_is_open()方法则用于验证服务器特定端口是否开放,如果开放则说明服务端还在线,不开放则说明服务端离线此处尝试等待一段时间后再次验证,在调用boost::bind()函数绑定套接字时通过&AsyncConnect::timer_handle()函数来设置一个超时等待时间。
进入到主函数中,首先程序通过while循环让程序保持持续运行,并通过hander.aysnc_connect(ep, 5000) 每隔5秒验证是否与服务端连接成功,如果连接了则进入内循环,在内循环中通过hander.port_is_open("127.0.0.1", 10000, 5000)验证特定端口是否开放,这主要是为了保证服务端断开后客户端依然能够跳转到外部循环继续等待服务端上线。而当客户端与服务端建立连接后则会持续在内循环中socket.read_some()接收服务端传来的特定命令,以此来执行不同的操作。
  1. #define BOOST_BIND_GLOBAL_PLACEHOLDERS
  2. #include <iostream>
  3. #include <string>
  4. #include <boost/asio.hpp>
  5. #include <boost/bind.hpp>  
  6. #include <boost/array.hpp>
  7. #include <boost/date_time/posix_time/posix_time_types.hpp>  
  8. #include <boost/noncopyable.hpp>
  9. using namespace std;
  10. using boost::asio::ip::tcp;
  11. // 异步连接地址与端口
  12. class AsyncConnect
  13. {
  14. public:
  15.         AsyncConnect(boost::asio::io_service& ios, tcp::socket &s)
  16.                 :io_service_(ios), timer_(ios), socket_(s) {}
  17.         // 异步连接
  18.         bool aysnc_connect(const tcp::endpoint &ep, int million_seconds)
  19.         {
  20.                 bool connect_success = false;
  21.                 // 异步连接,当连接成功后将触发 connect_handle 函数
  22.                 socket_.async_connect(ep, boost::bind(&AsyncConnect::connect_handle, this, _1, boost::ref(connect_success)));
  23.                 // 设置一个定时器  million_seconds
  24.                 timer_.expires_from_now(boost::posix_time::milliseconds(million_seconds));
  25.                 bool timeout = false;
  26.                 // 异步等待 如果超时则执行 timer_handle
  27.                 timer_.async_wait(boost::bind(&AsyncConnect::timer_handle, this, _1, boost::ref(timeout)));
  28.                 do
  29.                 {
  30.                         // 等待异步操作完成
  31.                         io_service_.run_one();
  32.                         // 判断如果timeout没超时,或者是连接建立了,则不再等待
  33.                 } while (!timeout && !connect_success);
  34.                 timer_.cancel();
  35.                 return connect_success;
  36.         }
  37.         // 验证服务器端口是否开放
  38.         bool port_is_open(std::string address, int port, int timeout)
  39.         {
  40.                 try
  41.                 {
  42.                         boost::asio::io_service io;
  43.                         tcp::socket socket(io);
  44.                         AsyncConnect hander(io, socket);
  45.                         tcp::endpoint ep(boost::asio::ip::address::from_string(address), port);
  46.                         if (hander.aysnc_connect(ep, timeout))
  47.                         {
  48.                                 io.run();
  49.                                 io.reset();
  50.                                 return true;
  51.                         }
  52.                         else
  53.                         {
  54.                                 return false;
  55.                         }
  56.                 }
  57.                 catch (...)
  58.                 {
  59.                         return false;
  60.                 }
  61.         }
  62. private:
  63.         // 如果连接成功了,则 connect_success = true
  64.         void connect_handle(boost::system::error_code ec, bool &connect_success)
  65.         {
  66.                 if (!ec)
  67.                 {
  68.                         connect_success = true;
  69.                 }
  70.         }
  71.         // 定时器超时timeout = true
  72.         void timer_handle(boost::system::error_code ec, bool &timeout)
  73.         {
  74.                 if (!ec)
  75.                 {
  76.                         socket_.close();
  77.                         timeout = true;
  78.                 }
  79.         }
  80.         boost::asio::io_service &io_service_;
  81.         boost::asio::deadline_timer timer_;
  82.         tcp::socket &socket_;
  83. };
  84. int main(int argc, char * argv[])
  85. {
  86.         try
  87.         {
  88.                 boost::asio::io_service io;
  89.                 tcp::socket socket(io);
  90.                 AsyncConnect hander(io, socket);
  91.                 boost::system::error_code error;
  92.                 tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 10000);
  93.                 // 循环验证是否在线
  94.         go_:  while (1)
  95.         {
  96.                 // 验证是否连接成功,并定义超时时间为5秒
  97.                 if (hander.aysnc_connect(ep, 5000))
  98.                 {
  99.                         io.run();
  100.                         std::cout << "已连接到服务端." << std::endl;
  101.                         // 循环接收命令
  102.                         while (1)
  103.                         {
  104.                                 // 验证地址端口是否开放,默认等待5秒
  105.                                 bool is_open = hander.port_is_open("127.0.0.1", 10000, 5000);
  106.                                 // 客户端接收数据包
  107.                                 boost::array<char, 4096> buffer = { 0 };
  108.                                 // 如果在线则继续执行
  109.                                 if (is_open == true)
  110.                                 {
  111.                                         socket.read_some(boost::asio::buffer(buffer), error);
  112.                                         // 判断收到的命令是否为GetCPU
  113.                                         if (strncmp(buffer.data(), "GetCPU", strlen("GetCPU")) == 0)
  114.                                         {
  115.                                                 std::cout << "获取CPU参数并返回给服务端." << std::endl;
  116.                                                 socket.write_some(boost::asio::buffer("CPU: 15 %"));
  117.                                         }
  118.                                         // 判断收到的命令是否为GetMEM
  119.                                         if (strncmp(buffer.data(), "GetMEM", strlen("GetMEM")) == 0)
  120.                                         {
  121.                                                 std::cout << "获取MEM参数并返回给服务端." << std::endl;
  122.                                                 socket.write_some(boost::asio::buffer("MEM: 78 %"));
  123.                                         }
  124.                                         // 判断收到的命令是否为终止程序
  125.                                         if (strncmp(buffer.data(), "Exit", strlen("Exit")) == 0)
  126.                                         {
  127.                                                 std::cout << "终止客户端." << std::endl;
  128.                                                 return 0;
  129.                                         }
  130.                                 }
  131.                                 else
  132.                                 {
  133.                                         // 如果连接失败,则跳转到等待环节
  134.                                         goto go_;
  135.                                 }
  136.                         }
  137.                 }
  138.                 else
  139.                 {
  140.                         std::cout << "连接失败,正在重新连接." << std::endl;
  141.                 }
  142.         }
  143.         }
  144.         catch (...)
  145.         {
  146.                 return false;
  147.         }
  148.         std::system("pause");
  149.         return 0;
  150. }
复制代码
AsyncTcpServer 类调用

服务端首先定义CEventHandler类并继承自CAsyncTcpServer::IEventHandler接口,该类内需要我们实现三个方法,方法ClientConnected用于在客户端连接时触发,方法ClientDisconnect则是在登录客户端离开时触发,而当客户端有数据发送过来时则ReceiveData方法则会被触发。
方法ClientConnected当被触发时自动将clientId客户端Socket套接字放入到tcp_client_id全局容器内存储起来,而当ClientDisconnect客户端退出时,则直接遍历这个迭代容器,找到序列号并通过tcp_client_id.erase将其剔除;
  1. #ifdef _MSC_VER
  2. #define BOOST_BIND_GLOBAL_PLACEHOLDERS
  3. #define _WIN32_WINNT 0x0601
  4. #define _CRT_SECURE_NO_WARNINGS
  5. #endif
  6. #pragma once
  7. #include <thread>
  8. #include <array>
  9. #include <boost\bind.hpp>
  10. #include <boost\noncopyable.hpp>
  11. #include <boost\asio.hpp>
  12. #include <boost\asio\placeholders.hpp>
  13. using namespace boost::asio;
  14. using namespace boost::asio::ip;
  15. using namespace boost::placeholders;
  16. using namespace std;
  17. // 每一个套接字连接,都自动对应一个Tcp客户端连接
  18. class CTcpConnection
  19. {
  20. public:
  21.         CTcpConnection(io_service& ios, int clientId) : m_socket(ios), m_clientId(clientId){}
  22.         ~CTcpConnection(){}
  23.         int                        m_clientId;
  24.         tcp::socket                m_socket;
  25.         array<BYTE, 16 * 1024>     m_buffer;
  26. };
  27. typedef shared_ptr<CTcpConnection> TcpConnectionPtr;
  28. class CAsyncTcpServer
  29. {
  30. public:
  31.         class IEventHandler
  32.         {
  33.         public:
  34.                 IEventHandler(){}
  35.                 virtual ~IEventHandler(){}
  36.                 virtual void ClientConnected(int clientId) = 0;
  37.                 virtual void ClientDisconnect(int clientId) = 0;
  38.                 virtual void ReceiveData(int clientId, const BYTE* data, size_t length) = 0;
  39.         };
  40. public:
  41.         CAsyncTcpServer(int maxClientNumber, int port);
  42.         ~CAsyncTcpServer();
  43.         void AddEventHandler(IEventHandler* pHandler){ m_EventHandlers.push_back(pHandler); }
  44.         void Send(int clientId, const BYTE* data, size_t length);
  45.         string GetRemoteAddress(int clientId);
  46.         string GetRemotePort(int clientId);
  47. private:
  48.         void bind_hand_read(CTcpConnection* client);
  49.         void handle_accept(const boost::system::error_code& error);
  50.         void handle_read(CTcpConnection* client, const boost::system::error_code& error, size_t bytes_transferred);
  51. private:
  52.         thread m_thread;
  53.         io_service m_ioservice;
  54.         io_service::work m_work;
  55.         tcp::acceptor m_acceptor;
  56.         int m_maxClientNumber;
  57.         int m_clientId;
  58.         TcpConnectionPtr m_nextClient;
  59.         map<int, TcpConnectionPtr> m_clients;
  60.         vector<IEventHandler*> m_EventHandlers;
  61. };
复制代码
而ReceiveData一旦收到数据,则直接将其打印输出到屏幕,即可实现客户端参数接收的目的;
[code]// 客户端获取数据virtual void ReceiveData(int clientId, const BYTE* data, size_t length){        std::cout

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

宝塔山

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表