提升asio关闭绑定套接字

时间:2016-06-24 22:25:57

标签: c++ boost-asio

在第一次运行时 - 绑定成功,当我重新启动程序时 - 错误10048(地址已经使用)

没有调用close和shutdown - 重启一切都很好

boost::asio::io_service _ioService;
boost::asio::ip::tcp::socket _socket(_ioService);


boost::system::error_code err;
_socket.open(boost::asio::ip::tcp::v4(), err);
if (err.value())
{
    cout<<err.value()<<endl;
    cout << err.message() << endl;
}

_socket.bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), 1276), err);
cout << err.value() << endl;

if (err.value())
{
    cout << err.value() << endl;
    cout << err.message() << endl;
}

_socket.connect(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), 1500), err);
if (err.value())
{
    cout << err.value() << endl;
    cout << err.message() << endl;
}

_socket.shutdown(_socket.shutdown_both);
_socket.close(err);

if (err.value())
{
    cout << err.value() << endl;
    cout << err.message() << endl;
}

1 个答案:

答案 0 :(得分:1)

问题是,套接字可能已进入TIME-WAIT状态。见Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

您可以设置重复使用地址的选项:这应该会阻止TIME-WAIT this explanation和更全面的版本here

在Boost.ASIO中,您可以这样做:

//Add this

boost::asio::socket_base::reuse_address reuse_address_option(true);
m_socket.set_option(reuse_address_option);

m_socket.bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("127.0.0.1"), 1250), err);

修改

在挖掘source code of acceptor之后,源文档中有一个示例,转载于此处

// @par Example
// Opening a socket acceptor with the SO_REUSEADDR option enabled:
// @code
boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen();