理解 boost::asio async_read 无书可读时的行为

understand boost::asio async_read behavior when there is nothing to read

我想了解当没有什么可读的时候 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.68.0) documentation:

This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

所以在服务器关闭连接(导致错误)之前什么都不会发生。

您可以自己测试一下:

#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";
    }
}

启动一个在本地主机端口 8000 上不响应的服务器(或更改代码)。例如。类似于 nc -l 8000python -m SimpleHTTPServer。然后 运行 程序并等待。什么都没发生。现在停止服务器,在我的 (Windows) 机器上这导致:

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