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

相关内容

热门资讯

分享开挂内幕辅助器!开元绍兴游... 分享开挂内幕辅助器!开元绍兴游戏辅助器AIapp,开元绍兴游戏多功能都是有辅助器app1、玩家可以在...
一分钟快速了解透视挂!宁波游戏... 一分钟快速了解透视挂!宁波游戏大厅透视挂AI软件,宁波游戏大厅多功能一贯存在有透视挂软件1)宁波游戏...
一秒答解透视挂!微乐捉老麻子透... 一秒答解透视挂!微乐捉老麻子透视挂AIapp,微乐捉老麻子多功能都是是有透视挂app微乐捉老麻子脚本...
玩家亲测透视挂!微乐a3纸牌透... 玩家亲测透视挂!微乐a3纸牌透视挂AI教程,微乐a3纸牌多功能一直存在有透视挂教程1、该软件可以轻松...
玩家必看分享辅助!朋朋棋牌辅助... 玩家必看分享辅助!朋朋棋牌辅助AI攻略,朋朋棋牌多功能其实真的是有辅助攻略1、全新机制【朋朋棋牌ai...
分享一款透视挂!海豚大厅透视挂... 分享一款透视挂!海豚大厅透视挂AI插件,海豚大厅多功能本来有透视挂插件海豚大厅透视方法中分为三种模型...
玩家必看科普辅助器!乐乐上海麻... 玩家必看科普辅助器!乐乐上海麻将辅助器AI插件,乐乐上海麻将多功能真是有辅助器插件进入游戏-大厅左侧...
玩家必看教程!大赢家跑得快开挂... 玩家必看教程!大赢家跑得快开挂功能技巧,大赢家跑得快确实真的是有开挂技巧(有辅助挂教学)1、在大赢家...
玩家攻略推荐!德州扑克辅助器功... 玩家攻略推荐!德州扑克辅助器功能攻略,德州扑克好像有辅助器攻略(真的有辅助挂)1)德州扑克免费钻石:...
推荐一款!一起斗地主辅助功能神... 推荐一款!一起斗地主辅助功能神器,一起斗地主其实存在有辅助神器(有辅助挂教学)1、首先打开一起斗地主...