【问题标题】:Can't exclusively bind to the network port with boost asio无法使用 boost asio 独占绑定到网口
【发布时间】:2015-12-26 16:10:49
【问题描述】:

我使用 boost asio 开发服务器应用程序。应用程序很好用。不行的,是对网口的独占绑定。

例子:

void testPortBinding()
{
    boost::asio::io_service _ioService;
    int serverPort = 10000;
    auto endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), serverPort);
    boost::shared_ptr<boost::asio::ip::tcp::acceptor> tcpAcceptor(new boost::asio::ip::tcp::acceptor(_ioService, endpoint));

    boost::this_thread::sleep(boost::posix_time::time_duration(0, 0, 30, 0));
}

int main()
{
    testPortBinding();

    return 0;
}

例如,我们同时启动了此类应用的两个实例。两个进程都绑定到网络端口并休眠 30 秒。

使用Windows工具Resource Monitor的标签Network我们看到第一个启动的进程正在监听网络端口10000,第二个进程没有监听任何端口。 在第一个进程停止后 - 第二个进程开始监听网络端口10000

所以看起来第二个进程一直在等待,直到第一个进程停止侦听 TCP 端口。

期望行为:应用绑定到 TCP 端口,如果 TCP 端口已使用,则停止。 所以在这个测试用例中,第二个进程应该异常停止。

如何实现这样的行为?

【问题讨论】:

  • 您可以自己发布答案作为答案。

标签: c++ boost network-programming boost-asio


【解决方案1】:

答案很简单——我们需要将选项reuse_address 设置为false。 new boost::asio::ip::tcp::acceptor(_ioService, endpoint, false) 完美运行。此选项的说明 - asio docs

【讨论】:

    猜你喜欢
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    相关资源
    最近更新 更多