3

I am required to set the options boost::asio::ip::tcp::no_delay and boost::asio::socket_base::linger for a boost::asio::ip::tcp::socket that connects to a remote TCP server. I used the method set_option in order to achieve this without any problems.

The question(s): once the io_service is run()ing and the socket opened, if I'm asked to change its options (i.e.: due to a change in the program configuration), can I do it with the socket opened? Do I need to close it before changing the options? Will it explode in my face if I don't close it? What is the best practice regarding this?

I wasn't able to find anything regarding this within the documentation.

Thank you in advance.

Nacho
  • 1,104
  • 1
  • 13
  • 30

1 Answers1

4

I have done some testing.

Before you set_option or get_option from a socket you must open it. Otherwise you get the error "The file handle supplied is not valid".

After closing the socket and opening it again, all options "go back" to default. So you need to set_options every time after open. I've found the best place for me to do this was within the callback passed to async_connect.

Example call to async_connect:

socketPtr->async_connect(endpoint_iter->endpoint(),
  boost::bind(&ConnectCallback, 
  shared_from_this(), 
  boost::asio::placeholders::error));

Callback definition:

void ConnectCallback(const boost::system::error_code& ec)
{
  if (!ec)
  {
    // Set options here
    boost::asio::socket_base::linger optionLinger(true, 0);
    socketPtr->set_option(optionLinger);

    boost::asio::ip::tcp::no_delay optionNoDelay(true);
    socketPtr->set_option(optionNoDelay);

    // Do what you must with the socket now, for instance async_read_some
    socketPtr->async_read_some(boost::asio::buffer(buffer, BUFFER_LENGTH),
      boost::bind(&ReadCallback, 
      shared_from_this(), 
      boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));
  }
}
Nacho
  • 1,104
  • 1
  • 13
  • 30