问题
I am trying to disable the Nagle Algorithm using the answer for the same question: 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;
and when running the code this error appears:
set_option: Bad file descriptor
How can I solve this problem?
回答1:
Where you set the option, the stream is still invalid (not open).
Wait until the socket is open, before setting the option:
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";
}
(We send main.cpp
to port 6666 using netcat there)
来源:https://stackoverflow.com/questions/30685502/iostream-and-no-delay-option