简体   繁体   English

C++ boost 1.72 重新连接 tcp::socket 在 linux 上抛出 WSAEADDRINUSE 异常,但适用于 Windows

[英]C++ boost 1.72 reconnect on tcp::socket throwing an exception with WSAEADDRINUSE on linux, but works on Windows

Hi my code works properly on windows but on linux the reconnect feature doesn't work,it throws an exception with WSAEADDRINUSE value.嗨,我的代码在 windows 上正常工作,但在 linux 上,重新连接功能不起作用,它会抛出WSAEADDRINUSE值的异常。

pClientSocket = new tcp::socket(*pIO_context, tcp::endpoint(boost::asio::ip::make_address(127.0.0.1, 50001));

First time it works on both Windows and Linux, but when i close the socket and try to connect again, i am getting an exception as described above only on linux OS.第一次它在 Windows 和 Linux 上工作,但是当我关闭套接字并尝试再次连接时,我得到一个异常,如上所述,仅在 linux 操作系统上。

Here is the close socket code.这是关闭套接字代码。

boost::system::error_code ec;
pClientSocket->shutdown( boost::asio::socket_base::shutdown_type::shutdown_receive, ec);
pClientSocket->close(eCode);

delete pClientSocket;

pClientSocket= nullptr;

Try using the reuse option:尝试使用重用选项:

boost::asio::socket_base::reuse_address option(true);
socket.set_option(option);

Update:更新:

This usually happens we you try to bind a server socket to an address that is already in use or it has been used recently (and the socket is still waiting to be cleaned up by the OS).这通常发生在我们尝试将服务器套接字绑定到已在使用或最近使用过的地址(并且套接字仍在等待操作系统清理)时。

With client sockets this is less common, you will have to force a port -by calling bind()- in the socket in order for this to happen.对于客户端 sockets,这种情况不太常见,您必须通过在套接字中调用 bind()- 来强制端口才能发生这种情况。

Now the code:现在代码:

pClientSocket = new tcp::socket(*pIO_context, tcp::endpoint(boost::asio::ip::make_address(127.0.0.1, 50001)); 
boost::asio::socket_base::reuse_address option(true); 
socket.set_option(option);

Calls this constructor overload.调用构造函数重载。 This constructor creates the socket and tries to bind it to the specified address.此构造函数创建套接字并尝试将其绑定到指定地址。 It fails because you didn't had the chance to specify the reuse option.它失败了,因为您没有机会指定重用选项。

On the other hand, this code:另一方面,这段代码:

pClientSocket = new tcp::socket(*pIO_context); 
pClientSocket->open(boost::asio::ip::tcp::v4()); 
pClientSocket->set_option(socket_base::reuse_address(true));

boost::system::error_code ec; 
pClientSocket->bind(tcp::endpoint(make_address(127.0.0.1, 50001), ec); 
if (ec) { }

Calls this constructor overload, which just creates the socket but doesn't open no connect it.调用构造函数重载,它仅创建套接字但不打开或连接它。 This allows to specify any socket option before bind/connect, etc.这允许在绑定/连接等之前指定任何套接字选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM