C++ boost::asio编程-异步TCP详解及实例代码

 更新时间:2020年4月25日 17:33  点击:2273

C++ boost::asio编程-异步TCP

大家好,我是异步方式

和同步方式不同,我从来不花时间去等那些龟速的IO操作,我只是向系统说一声要做什么,然后就可以做其它事去了。如果系统完成了操作, 系统就会通过我之前给它的回调对象来通知我。
在ASIO库中,异步方式的函数或方法名称前面都有“async_ ” 前缀,函数参数里会要求放一个回调函数(或仿函数)。异步操作执行 后不管有没有完成都会立即返回,这时可以做一些其它事,直到回调函数(或仿函数)被调用,说明异步操作已经完成。

在ASIO中很多回调函数都只接受一个boost::system::error_code参数,在实际使用时肯定是不够的,所以一般 使用仿函数携带一堆相关数据作为回调,或者使用boost::bind来绑定一堆数据。

另外要注意的是,只有io_service类的run()方法运行之后回调对象才会被调用,否则即使系统已经完成了异步操作也不会有任 务动作。

好了,就介绍到这里,下面是我带来的异步方式TCP Helloworld服务器端:

// BoostTcpServer.cpp : 定义控制台应用程序的入口点。 
// 
 
#include "stdafx.h" 
#include "boost/asio.hpp" 
#include "boost/shared_ptr.hpp" 
#include "boost/thread.hpp" 
 
using namespace std; 
using namespace boost::asio; 
 
#ifdef _MSC_VER 
#define _WIN32_WINNT  0X0501 //避免VC下编译警告 
#endif 
 
#define PORT 1000 
#define IPV6 
//#define IPV4 
 
class AsyncServer 
{ 
public: 
  //构造函数 
  AsyncServer(io_service &io,ip::tcp::endpoint &ep):ios(io),acceptor(io,ep) 
  { 
    //acceptor(ios,ep); 
    start(); 
  } 
  //启动异步接受客户端连接 
  void start() 
  { 
    sock_ptr sock(new ip::tcp::socket(ios)); 
    //当有连接进入时回调accept_handler函数 
    acceptor.async_accept(*sock, 
      boost::bind(&AsyncServer::accept_handler,this,placeholders::error,sock)); 
  } 
private: 
  io_service &ios; 
  ip::tcp::acceptor acceptor; 
  typedef boost::shared_ptr<ip::tcp::socket> sock_ptr; 
 
  void accept_handler(const boost::system::error_code &ec, sock_ptr sock) 
  { 
    if(ec)  
      return; 
    //输出客户端连接信息 
    std::cout <<"remote ip:"<<sock->remote_endpoint().address()<<endl; 
    std::cout <<"remote port:"<<sock->remote_endpoint().port() << std::endl; 
    //异步向客户端发送数据,发送完成时调用write_handler 
    sock->async_write_some(buffer("I heard you!"), 
      bind(&AsyncServer::write_handler,this,placeholders::error)); 
    //再次启动异步接受连接 
    start(); 
  } 
 
  void write_handler(const boost::system::error_code&) 
  { 
    cout<<"send msg complete!"<<endl; 
  } 
}; 
 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
  try 
  { 
    //定义io_service对象 
    io_service ios; 
    //定义服务端endpoint对象(协议和监听端口) 
#ifdef IPV4 
    ip::tcp::endpoint serverep(ip::tcp::v4(),PORT); 
#endif 
 
#ifdef IPV6 
    ip::tcp::endpoint serverep(ip::tcp::v6(),PORT); 
#endif 
    //启动异步服务 
    AsyncServer server(ios, serverep); 
    //等待异步完成 
    ios.run(); 
  } 
  catch (std::exception& e) 
  { 
    cout<<e.what()<<endl; 
  } 
  return 0; 
}

客户端一般无需采用异步方式,同同步方式即可。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

[!--infotagslink--]

相关文章