问题
I try to use a boost asio socket, bound to a local address/port combination. That works great. What doesn't work, is the re-using of the socket once the socket and application has been stopped and restarted.
//
// open the socket - it would also be opened by the async_connect()
// method but we might need an open socket to bind it
_socket.open(boost::asio::ip::tcp::v4());
if ( _bindLocal ) {
boost::asio::socket_base::reuse_address option(true);
_socket.set_option(option);
_socket.bind( _localEndpoint );
}
// Invoke async. connect. Immediate return, no throw.
_socket.async_connect(_remoteEndpoint,
boost::bind(&MyTransceiver::handleConnect, this,
boost::asio::placeholders::error));
What am I missing? Is the ordering of the open(), set_option() and bind() call correct?
回答1:
The code looks fine. Try to use error_code to get the result of your set_option() call.
boost::system::error_code ec;
_socket.set_option(boost::asio::socket_base::reuse_address(true), ec);
来源:https://stackoverflow.com/questions/8433070/socket-reusing-with-boost-asio