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