我对boost::asio
基础知识不是很熟悉。我正在处理一项已连接到 Web 服务器并读取响应的任务。响应是在随机周期内抛出的,即生成响应时。
为此,我正在使用包含基础知识的boost::beast
库boost::asio
。
我发现该async_read()
函数正在等待,直到它收到响应。
现在,事情是:在文档和示例中,websocket 通信的异步方式显示在 websocket 在收到响应后关闭的位置。
这是通过此代码(野兽文档)完成的:
void read_resp(boost::system::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if(ec)
return fail(ec, "write");
// Read a message into our buffer
ws_.async_read(buffer_, std::bind(&session::close_ws_, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
void close_ws_(boost::system::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if(ec)
return fail(ec, "read");
// Close the WebSocket connection
ws_.async_close(websocket::close_code::normal, std::bind(&session::on_close, shared_from_this(), std::placeholders::_1));
}
在这个程序中,假设发送在接收之前完成。并且只有一次响应来自服务器的期望。之后,它(客户端)继续前进并关闭 websocket。
但在我的程序中:
我必须检查写作部分是否已经结束,如果没有,在写作过程中,websocket 应该来检查到目前为止所写内容的响应。
现在为此,我放了一个 if else 来告诉我的程序我的写作是否完成?如果没有,那么程序应该回到写入部分并编写所需的东西。如果是,然后关闭连接。
void write_bytes(//Some parameters) {
//write on websocket
//go to read_resp
}
void read_resp(boost::system::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if(ec)
return fail(ec, "write");
// Read a message into our buffer
if (write_completed){
ws_.async_read(buffer_, std::bind(&session::close_ws_, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
} else {
ws_.async_read(buffer_, std::bind(&session::write_bytes, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
}
void close_ws_(//Some parameters) {
//Same as before
}
现在我要做的是,写入完成后等待3秒,每1秒读取一次websocket,3秒后关闭websocket。
为此,我又添加了一个 if else 来检查 3 秒条件read_resp
void read_resp(boost::system::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if(ec)
return fail(ec, "write");
// Read a message into our buffer
if (write_completed){
if (3_seconds_completed) {
ws_.async_read(buffer_, std::bind(&session::close_ws_, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
} else {
usleep(1000000); //wait for a second
ws_.async_read(buffer_, std::bind(&session::read_resp, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
} else {
ws_.async_read(buffer_, std::bind(&session::write_bytes, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
}
但是 websocket 正在等待async-read
接收某些东西,这样做只会进入会话超时。
如何只查看是否有要读取的内容,然后继续执行回调?