有人提到了TCP套接字的keepAlive功能。以下是对其进行了很好的描述:
http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html
我是这样使用它的:在套接字连接后,我调用这个函数来设置keepAlive。 keepAliveTime
参数指定在没有活动的情况下,直到发送第一个keep-alive数据包的超时时间(以毫秒为单位)。keepAliveInterval
参数指定如果没有收到确认,连续发送keep-alive数据包之间的时间间隔(以毫秒为单位)。
void SetKeepAlive(bool on, uint keepAliveTime, uint keepAliveInterval)
{
int size = Marshal.SizeOf(new uint());
var inOptionValues = new byte[size * 3];
BitConverter.GetBytes((uint)(on ? 1 : 0)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)keepAliveTime).CopyTo(inOptionValues, size);
BitConverter.GetBytes((uint)keepAliveInterval).CopyTo(inOptionValues, size * 2);
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
我也在使用异步阅读:
socket.BeginReceive(packet.dataBuffer, 0, 128,
SocketFlags.None, new AsyncCallback(OnDataReceived), packet)
在回调函数中,捕获了超时引发的SocketException
,当套接字在保持活动数据包后没有收到ACK信号时会出现该异常。
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
int iRx = socket.EndReceive(asyn);
}
catch (SocketException ex)
{
SocketExceptionCaught(ex);
}
}
这样,我就能够安全地检测TCP客户端和服务器之间的断开连接。