iostream 和 No_delay 选项

iostream and No_delay option

我正在尝试使用同一问题的答案禁用 Nagle 算法:ASIO ip::tcp::iostream and TCP_NODELAY:

    boost::asio::ip::tcp::iostream socketStream;
    const boost::asio::ip::tcp::no_delay option( true );
    socketStream.rdbuf()->set_option( option );
    boost::asio::io_service io_service;
    tcp::endpoint endpoint (tcp::v4 (), 6666);
    tcp::acceptor acceptor (io_service, endpoint);

    std::cout << "Waiting for connection.." << std::endl;
    acceptor.accept (*socketStream.rdbuf ());
    std::cout << "Connected!" << std::endl;

当 运行 代码出现此错误时:

set_option: Bad file descriptor

我该如何解决这个问题?

设置选项的地方,流仍然无效(未打开)。

等到套接字打开,再设置选项:

Live On Coliru

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

static boost::asio::ip::tcp::no_delay const no_delay_option (true);

int main() {
    using boost::asio::ip::tcp;

    tcp::iostream socketStream;


    boost::asio::io_service io_service;

    tcp::endpoint endpoint (tcp::v4(), 6666);
    tcp::acceptor acceptor (io_service, endpoint);

    std::cout << "Waiting for connection.." << std::endl;
    acceptor.accept (*socketStream.rdbuf ());
    socketStream.rdbuf()->set_option(no_delay_option);

    std::cout << "Connected!" << std::endl;
    std::cout << socketStream.rdbuf() << "\n";
}

(我们使用 netcat 将 main.cpp 发送到端口 6666)