我使用 boost asio 开发服务器应用程序。应用程序运行良好。不起作用的是对网络端口的独占绑定(bind)。
例子:
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;
}
例如,我们同时启动了此类应用的两个实例。两个进程都绑定(bind)到网络端口并休眠 30 秒。
使用 Windows 工具 Resource Monitor
的标签 Network
我们看到第一个启动的进程监听网络端口 10000
而第二个进程没有监听任何端口。
在第一个进程停止后 - 第二个进程开始监听网络端口 10000
。
所以看起来第二个进程一直等到第一个进程停止监听 TCP 端口。
期望的行为:应用程序绑定(bind)到 TCP 端口或如果 TCP 端口已被使用则停止。 所以在这个测试用例中,第二个进程应该异常停止。
如何实现这样的行为?
最佳答案
答案很简单 - 我们需要将选项 reuse_address
设置为 false。 new boost::asio::ip::tcp::acceptor(_ioService, endpoint, false)
完美运行。此选项的说明 - asio docs
关于c++ - 无法使用 boost asio 专门绑定(bind)到网络端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34473012/