当没有什么要阅读时,了解boost :: asio async_read行为

时间:2018-11-05 17:31:12

标签: c++ boost-asio

我正试图了解async_read在没有什么可阅读的情况下会发生什么。

例如,客户端创建与服务器的连接,然后启动async_read(),但是该服务器不希望向该客户端发送任何内容。那会发生什么呢?我应该收到EOF吗?

更新数据: 我认为@ user786653是正确的。我做了一个简单的例子(见下文)。

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/asio.hpp>

class test{
public:
test(boost::asio::io_service& io_service):_socket(io_service){
}

void handle_connect(){
    std::cout<<"entering test::handle_connect"<<std::endl;
    char reply[128];
        boost::asio::async_read(_socket, boost::asio::buffer(reply, sizeof(reply)),
                            [](boost::system::error_code ec, std::size_t /*length*/){
                std::cout<<"Read result:"<< ec<<" - "<<ec.message()<<std::endl;
            });
}

boost::asio::ip::tcp::socket & socket(){
    return _socket;
}

private:
boost::asio::ip::tcp::socket _socket;
};



int main() {
try {
boost::asio::io_service io_service;
boost::asio::ip::tcp::socket s(io_service);
boost::asio::ip::tcp::resolver resolver(io_service);
    boost::asio::ip::tcp::resolver::query query("127.0.0.1", "8000");
    boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    boost::asio::ip::tcp::endpoint endpoint = *endpoint_iterator;

test t(io_service);
t.socket().async_connect(endpoint,boost::bind(&test::handle_connect, &t));

io_service.run();
} catch (std::exception& e) {
    std::cerr << "Exception: " << e.what() << "\n";
}
}

1 个答案:

答案 0 :(得分:0)

引自最新版本(1.68.0)documentation

  

此函数用于从流中异步读取一定数量的数据字节。函数调用总是立即返回。异步操作将继续,直到满足以下条件之一:

     
      
  • 提供的缓冲区已满。也就是说,传输的字节等于缓冲区大小的总和。
  •   
  • 发生错误。
  •   

因此,在服务器关闭连接之前不会发生任何事情(导致错误)。

您可以自己测试一下:

#include <iostream>
#include <boost/asio.hpp>
int main() {
    try {
        boost::asio::io_context io_context;
        boost::asio::ip::tcp::socket s(io_context);
        boost::asio::ip::tcp::resolver resolver(io_context);
        boost::asio::connect(s, resolver.resolve("localhost", "8000"));
        char reply[128];
        async_read(s, boost::asio::buffer(reply, sizeof(reply)), [](boost::system::error_code ec, std::size_t /*length*/) {
                std::cout << "Read result: " << ec << " - " << ec.message() << "\n";
                });
        io_context.run();
    } catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }
}

启动一个在localhost端口8000上没有响应的服务器(或更改代码)。例如。 nc -l 8000python -m SimpleHTTPServer之类的东西。然后运行程序并等待。什么都没发生。现在停止服务器,在我的(Windows)计算机上,结果为:

Read result: system:10054 - An existing connection was forcibly closed by the remote host