gpt4 book ai didi

c# - 断开 TCPClient 并在另一端看到

转载 作者:行者123 更新时间:2023-11-30 19:33:24 30 4
gpt4 key购买 nike

我正在尝试断开客户端与服务器的连接,但服务器仍将其视为已连接。我找不到解决这个问题的方法,关机、断开连接和关闭都不起作用。

我与客户端断开连接并检查服务器的一些代码:

客户:

  private void btnDisconnect_Click(object sender, EventArgs e)
{
connTemp.Client.Shutdown(SocketShutdown.Both);
connTemp.Client.Disconnect(false);
connTemp.GetStream().Close();
connTemp.Close();
}

服务器:

    while (client != null && client.Connected)
{
NetworkStream stream = client.GetStream();
data = null;

try
{
if (stream.DataAvailable)
{
data = ReadStringFromClient(client, stream);
WriteToConsole("Received Command: " + data);
}
} // So on and so on...

代码中有更多的写入和读取。

希望大家帮帮忙。

更新:我什至尝试通过 ref 传递 TCP 客户端,假设存在范围问题并且即使在读取之后 client.Connected 仍然为真。出了什么问题?

第二次更新!!:

这是解决方案。偷看一下,并据此确定您是否已连接。

  if (client.Client.Poll(0, SelectMode.SelectRead))
{
byte[] checkConn = new byte[1];
if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0)
{
throw new IOException();
}
}

最佳答案

这里是解决方案!

  if (client.Client.Poll(0, SelectMode.SelectRead))
{
byte[] checkConn = new byte[1];
if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0)
{
throw new IOException();
}
}

关于c# - 断开 TCPClient 并在另一端看到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3782471/

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