Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying boost::asio::socket::set_option

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.

like image 805
Nacho Avatar asked Dec 15 '25 00:12

Nacho


1 Answers

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));
  }
}
like image 87
Nacho Avatar answered Dec 16 '25 15:12

Nacho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!