如果我的客户端连接断开了end( kill -9 server).客户端需要几分钟才能确定出现问题.Socket.Connected即使连接实际上已断开,也会返回true.
一旦另一端断开链接,确定连接不存在的最快方法是什么?
try{
Socket socket= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
/*Assume there is a connection on the other end*/
while (socket.Connected)
{
/*Do some processing*/
}
}catch (SocketException se){
Console.WriteLine(ex.Message);
} catch (Exception ex){
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("something bad happen");
}
Run Code Online (Sandbox Code Playgroud)
小智 3
这似乎对我有用......有人看到任何问题吗?
public bool IsConnected
{
get {return !(Socket.Poll(1, SelectMode.SelectRead)
&& m_socket.Available ==0)}
}
Run Code Online (Sandbox Code Playgroud)
也可以放入扩展方法中。
public static class SocketExtensions
{
public static bool IsConnected(this Socket @this)
{
return !(@this.Poll(1, SelectMode.SelectRead) && @this.Available == 0);
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以在处理套接字的代码中轻松使用它。
var mySocket = new Socket();
while(mySocket.IsConncted())
{
// Do Stuff
}
Run Code Online (Sandbox Code Playgroud)