socket断线如何重连
3个回答
推荐于2017-09-01 · 知道合伙人互联网行家
关注
展开全部
当Socket.Conneted == false时,调用如下函数进行判断:
///
/// 当socket.connected为false时,进一步确定下当前连接状态
///
///
private bool IsSocketConnected()
{
#region remarks
/********************************************************************************************
* 当Socket.Conneted为false时, 如果您需要确定连接的当前状态,请进行非阻塞、零字节的 Send 调用。
* 如果该调用成功返回或引发 WAEWOULDBLOCK 错误代码 (10035),则该套接字仍然处于连接状态;
* 否则,该套接字不再处于连接状态。
* Depending on
********************************************************************************************/
#endregion
#region 过程
// This is how you can determine whether a socket is still connected.
bool connectState = true;
bool blockingState = socket.Blocking;
try
{
byte[] tmp = new byte[1];
socket.Blocking = false;
socket.Send(tmp, 0, 0);
//Console.WriteLine("Connected!");
connectState = true; //若Send错误会跳去执行catch体,而不会执行其try体里其之后的代码
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
//Console.WriteLine("Still Connected, but the Send would block");
connectState = true;
}
else
{
//Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
connectState = false;
}
}
finally
{
socket.Blocking = blockingState;
}
//Console.WriteLine("Connected: {0}", client.Connected);
return connectState;
#endregion
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询