Asynchronousreadingfromboost::asiosocketwithtimeout
创始人
2024-09-21 04:30:29
0

在使用boost::asio套接字从网络中接收数据时,我们可能需要设置超时时间以确保操作不会无限期地阻塞。解决方法是使用基于时间的异步等待函数来实现超时读取。以下是一个示例代码:

#include #include #include #include

using boost::asio::ip::tcp;

class Session { public: Session(boost::asio::io_service& ios) : m_socket(ios), m_timer(ios) {}

tcp::socket& socket() { return m_socket; }

void start() { asyncRead(); }

private: void asyncRead() { m_socket.async_read_some(boost::asio::buffer(m_buffer), boost::bind(&Session::handleRead, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

m_timer.expires_from_now(std::chrono::seconds(10));
m_timer.async_wait(boost::bind(&Session::handleTimeout, this));

}

void handleRead(const boost::system::error_code& error, std::size_t bytes_transferred) { m_timer.cancel();

if (error) {
  std::cerr << "read error: " << error.message() << std::endl;
  return;
}

std::cout << "read " << bytes_transferred << " bytes: ";
std::cout.write(m_buffer.data(), bytes_transferred);
std::cout << std::endl;

asyncRead();

}

void handleTimeout() { std::cerr << "read timeout" << std::endl; m_socket.cancel(); }

tcp::socket m_socket; boost::asio::steady_timer m_timer; std::array m_buffer; };

int main() { try { boost::asio::io_service ios; tcp::acceptor acceptor(ios, tcp::endpoint(tcp::v4(), 12345));

while (true) {
  std::cout << "waiting for connection..." << std::endl;

  tcp::socket socket(ios);
  acceptor.accept

相关内容

热门资讯

透视教学“pokeplus脚本... 透视教学“pokeplus脚本”透视辅助工具(切实真的是有挂)1、pokeplus脚本系统规律教程、...
透视黑科技!德普之星私人局辅助... 透视黑科技!德普之星私人局辅助免费,(德普之星)总是是有挂,靠谱教程(有挂揭秘)所有人都在同一条线上...
透视免费!pokerworld... 透视免费!pokerworld修改器,pokermaster脚本,大神讲解(有挂脚本);该软件可以轻...
透视玄学!德扑圈透视,(德扑之... 透视玄学!德扑圈透视,(德扑之心)原来真的有挂,必备教程(有挂介绍)1、构建自己的德扑圈透视辅助插件...
透视软件!大菠萝789辅助器下... 透视软件!大菠萝789辅助器下载,德州来玩辅助器,揭秘攻略(有挂技巧)1、玩家可以在大菠萝789辅助...
透视讲解!德普软件,德普之星辅... 透视讲解!德普软件,德普之星辅助器怎么用,安装教程(有挂介绍)1、让任何用户在无需德普之星辅助器怎么...
透视新版“werplan辅助软... 透视新版“werplan辅助软件”透视辅助助手(总是有挂)1、不需要AI权限,帮助你快速的进行wer...
透视挂!德普之星辅助软件,(德... 透视挂!德普之星辅助软件,(德普之星)好像是有挂,新2025版(有挂教程);1、点击下载安装,德普之...
透视最新“智星菠萝辅助”透视辅... 透视最新“智星菠萝辅助”透视辅助脚本(一贯真的有挂)1、玩家可以在智星菠萝辅助软件透明挂俱乐部对游戏...
透视最新!德普之星透视,德普之... 透视最新!德普之星透视,德普之星辅助器app,黑科技教程(有挂详情)1)德普之星辅助器app辅助挂:...