Reputation: 2837
I develop server app using boost asio. App works great. What doesn't work, is the the exclusive binding to the network port.
Example:
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;
}
For example we launched two instances of such app at the same time. Both processes bind to the network port and sleep for 30 seconds.
Using tab Network
of Windows tool Resource Monitor
we see that the first launched process listening on the network port 10000
and second process do not listening any port.
Right after first process stopped - second process starts to listening on the network port 10000
.
So it looks like the second process waits until the first process stopped listening on TCP port.
Desired behavior: app binds to the TCP port or stops if TCP port already used. So in this test case second process should stop with exception.
How to achieve such behavior?
Upvotes: 1
Views: 579
Reputation: 2837
The answer is simple - we need to set option reuse_address
to false. new boost::asio::ip::tcp::acceptor(_ioService, endpoint, false)
works perfect. Description for this option - asio docs
Upvotes: 0