我正在尝试断开客户端与服务器的连接,但服务器仍将其视为已连接。我找不到解决方案,关机、断开连接和关闭都不起作用。
我与客户端断开连接并检查服务器的一些代码:
客户:
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();
}
}