gpt4 book ai didi

c# - .net套接字问题: client disconnect from server

转载 作者:行者123 更新时间:2023-12-03 12:01:31 25 4
gpt4 key购买 nike

在服务器端,我有这段代码在新线程中运行

static void ListenForConsultant()
{
while (true)
{
var serverSocket = new TcpListener(IPAddress.Any, 2111);
serverSocket.Start();
var clientSocket = serverSocket.AcceptTcpClient();
consultantConnected = true;
Console.WriteLine(" >> Consultant Connected");
byte[] bytesFrom = new byte[10025];
while (true)
{
if (!clientSocket.Connected)
{
break;
}
NetworkStream networkStream = clientSocket.GetStream();
bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
var dataFromConsultant = System.Text.Encoding.ASCII.GetString(bytesFrom);
if (dataFromConsultant.IndexOf("~") != -1 && dataFromConsultant.IndexOf("^") != -1 && dataFromConsultant.IndexOf("^") > dataFromConsultant.IndexOf("~"))
{
var lengthOfMessage = dataFromConsultant.IndexOf("^") - dataFromConsultant.IndexOf("~") - 1;
dataFromConsultant = dataFromConsultant.Substring(dataFromConsultant.IndexOf("~") + 1, lengthOfMessage);
Console.WriteLine(" >> From consultant:" + dataFromConsultant);
}

}

consultantConnected = false;
Console.WriteLine(" >> Consultant Disconnected");

serverSocket.Stop();
}
}

我使用腻子连接到端口2111。所有工作正常,但是当我关闭腻子 socket 时无法关闭,但是我有条件
if (!clientSocket.Connected)
{
break;
}

调试告诉我,即使我与服务器断开连接,clientSocket.Connected也为true。

为什么会这样?

最佳答案

tcpClient.Connected属性值不可靠,取决于最后一次通信;因此,如果最后一次通信成功,则其值为true,否则为false。有关该检查的更多信息this

使用此IsConnected属性检查tcpClient是否已连接:

public static bool IsConnected
{
get
{
try
{
//return _tcpClient != null && _tcpClient.Client != null && _tcpClient.Client.Connected;

if (_tcpClient != null && _tcpClient.Client != null && _tcpClient.Client.Connected)
{

/* As the documentation:
* When passing SelectMode.SelectRead as a parameter to the Poll method it will return
* -either- true if Socket.Listen(Int32) has been called and a connection is pending;
* -or- true if data is available for reading;
* -or- true if the connection has been closed, reset, or terminated;
* otherwise, returns false
*/

// Detect if client disconnected
if (_tcpClient.Client.Poll(0, SelectMode.SelectRead))
{
byte[] buff = new byte[1];
if (_tcpClient.Client.Receive(buff, SocketFlags.Peek) == 0)
{
// Client disconnected
return false;
}
else
{
return true;
}
}

return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
}

编辑:注意,检查 IsConnected不会阻止检查后断开连接。即有可能发生这样的情况,即在“评估 IsConnected检查并返回true之后”,就在连接套接字后立即断开连接,因此,您应将所有通信包装在 try/catchtry/catch/finally块中,以期望套接字可以随时断开连接。

关于c# - .net套接字问题: client disconnect from server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6641385/

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