foreach (var dic in sockets) { if (dic.Value.Poll(1000, SelectMode.SelectRead)) { dic.Value.Close();//关闭socket sockets.TryRemove(dic.Key, out Socket socket); _logger.Warn($"IP:{dic.Key},客户端socket连接断开;"); continue; } _logger.Info($"IP:{dic.Key},客户端socket连接正常;"); }
private ConcurrentDictionary<string, Socket> sockets = new ConcurrentDictionary<string, Socket>();确保线程安全
主要是利用socket的poll方法来进行判断。
另外我试了下使用KeepAlive,发现不起作用。但是如果放在客户端使用的话,就会起作用。不知道为什么。
参考网址:https://www.cnblogs.com/cuisir/p/8522680.html