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

相关内容

热门资讯

透明神器!传送屋潮州激k辅助怎... 透明神器!传送屋潮州激k辅助怎么打开,wepoker安装教程(辅助挂)详细开挂辅助挂 了解更多开挂安...
透明科技!乐酷副厅辅助,wep... >>您好:wepoker辅助器免费确实是有挂的,很多玩家在这款wepoker辅助器免费游戏中打牌都会...
透视辅助!雀姬辅助器,hhpo... 透视辅助!雀姬辅助器,hhpoker万能辅助器(辅助挂)详细开挂辅助器;无需打开直接搜索加(薇:13...
透明辅助!微信小程序有挂吗辅助... 透明辅助!微信小程序有挂吗辅助,we poker免费辅助器(辅助挂)详细开挂辅助软件;无需打开直接搜...
透视好牌!广东雀神辅助器,wp... 透视好牌!广东雀神辅助器,wpk透视怎么安装(辅助挂)详细开挂辅助安装;无需打开直接搜索加薇1367...
透明安装!小程序广东雀神智能插... 小程序广东雀神智能插件是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以...
透视科技!同城游微信游戏辅助,... 透视科技!同城游微信游戏辅助,wepoker手机助手(辅助挂)详细开挂辅助平台;无需打开直接搜索微信...
透视美元局!xpoker透视辅... 透视美元局!xpoker透视辅助,hardrock透视工具(辅助挂)详细开挂辅助软件;无需打开直接搜...
透明工具!游戏挂机辅助软件,红... 游戏挂机辅助软件是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微...
透明教学!决战卡五星辅助源码,... 透明教学!决战卡五星辅助源码,拱趴大菠萝万能辅助器(辅助挂)详细开挂辅助下载1、下载安装好拱趴大菠萝...