Socket reusing with boost asio

那年仲夏 提交于 2020-01-30 05:15:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!