我正在使用C#窗口应用程序窗体处理TCP多线程服务器,我正在尝试检测客户端的计算机是否已关闭并与服务器断开连接。我已经阅读了一些帖子并提出了一些想法:
How to determine if the tcp is connected or not?
Instantly detect client disconnection from server socket
但我不确定在哪里调用函数IsConnected
我的代码如下:
public BindingList<Tablet> tabletList = new BindingList<Tablet>();
private Socket socket_Server = null;
private Thread myThread = null;
private Socket socket_Connect = null;
private Dictionary<string, Socket> dic = new Dictionary<string, Socket> { };
private string RemoteEndPoint;
socket_Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ServerIP = IPAddress.Parse("192.168.2.146");
IPEndPoint point = new IPEndPoint(ServerIP, portNum);
socket_Server.Bind(point);
socket_Server.Listen(50);
myThread = new Thread(Listen_Disp);
myThread.IsBackground = true;
myThread.Start();
Console.WriteLine("Server start");
private void Listen_Disp()
{
try
{
while (true)
{
//This is not working
for (int i = 0; i < tabletList.Count; i++)
{
if (!SocketConnected(dic[tabletList[i].ip]))
{
Console.WriteLine(RemoteEndPoint + "disconnected");
}
}
try
{
socket_Connect = socket_Server.Accept();
RemoteEndPoint = socket_Connect.RemoteEndPoint.ToString();
Console.WriteLine(RemoteEndPoint + " is connected");
dic.Add(RemoteEndPoint, socket_Connect);
Tablet newTablet = new Tablet();
newTablet.ip = RemoteEndPoint;
newTablet.status = "Online";
tabletList.Add(newTablet);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.WriteLine("end of while");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static class SocketExtensions
{
public static bool IsConnected(this Socket socket)
{
try
{
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException) { return false; }
}
}
感谢您的帮助。
答案 0 :(得分:3)
关于这个问题有很多错误信息,其中一些错误信息存在于你所链接的问题中。检测TCP断开连接的唯一可靠方法是尝试写入连接。读取超时也可以指示连接断开,但也可能意味着很多其他事情,例如卡住的服务器。读数时的EOS条件表示正常断开连接。 IsConnected()方法和朋友只会向您提供您对此套接字所做的操作的历史记录:它们不会为您提供连接的当前状态。他们不能,因为,没有待处理的写请求,没有状态 知道。 TCP不会保留类似拨号音的任何内容。