gpt4 book ai didi

.net - 如何断开 TcpClient 以允许新连接?

转载 作者:可可西里 更新时间:2023-11-01 02:52:57 25 4
gpt4 key购买 nike

我有一个等待新套接字连接的 TcpListener。当建立新连接时,一些其他代码服务来自远程用户的消息。我会定期检查新连接,如果建立了新连接,则应删除旧连接。

以前我只是打开新连接,大部分情况下都可以正常工作。不过,有时我会在重新使用同一个端口时遇到问题,所以我认为关闭该连接会更好(我认为这也应该给老用户一个连接已终止的指示)。

下面的代码是我尝试这样做的,但由于某种原因,断开连接调用似乎无限期地阻塞。有办法阻止吗? ...还是我在这里遗漏了其他东西?

while(1)
{
// FYI, m_server is a TcpListener^ and m_client is a TcpClient^
// Check for new client connections
if (m_server->Pending() == true)
{
if( m_stream != nullptr )
{
m_client->Client->Shutdown( SocketShutdown::Both ); // Stop sending / receiving
m_client->Client->Disconnect(true); // Disconnect the underlying network stream
m_client->Client->Close(); // Disconnect the underlying network stream
m_client->Close();
delete m_client;
m_client = nullptr;
}

m_client = m_server->AcceptTcpClient(); //grab the TCP client
m_stream = m_client->GetStream(); //create the stream at the same time
}

// ...go and service pending messages on the client stream
}

The docs on the Disconnect() function建议我可以设置超时,但他们没有提到如何设置?

If you need to call Disconnect without first calling Shutdown, you can set the DontLinger Socket option to false and specify a nonzero time-out interval to ensure that data queued for outgoing transmission is sent. Disconnect then blocks until the data is sent or until the specified time-out expires. If you set DontLinger to false and specify a zero time-out interval, Close releases the connection and automatically discards outgoing queued data.

[编辑] 我通过将 m_client->Client->Disconnect(true); 更改为 m_client->Client- 找到了超时问题的解决方案>Disconnect(false); 但这仍然没有警告我的客户套接字已关闭。我已经尝试了所有我能想到的测试,但它们都成功了:

// m_client is a TcpClient^
bool stillConnected = ( (m_client != nullptr) &&
(m_client->Connected == true) &&
(m_client->Client != nullptr) &&
(m_client->Client->Connected == true) );

stillConnected 始终为真,即使在另一个客户端已连接到服务器并因此调用了上面的所有关闭操作之后也是如此。就像我在问题顶部提到的关机问题没有正确关闭套接字之类的?

最佳答案

当读取返回成功且长度为零字节时,检测到 TCP 套接字断开连接(FIN 标志从远程端发送)。

关于.net - 如何断开 TcpClient 以允许新连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4827080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com