在C#中利用Keep-Alive处理Socket网络异常断开的方法
网络异常断开原因主要有那些呢?归纳起来主要有以下两种:1、客户端程序异常。 对于这种情况,我们很好处理,因为客户端程序异常退出会在服务端引发ConnectionReset的Socket异常(就是WinSock2中的10054异常)。只要在服务端处理这个异常就可以了。 2、网络链路异常。 如:网线拔出、交换机掉电、客户端机器掉电。当出现这些情况的时候服务端不会出现任何异常。这样的话上面的代码就不能处理这种情况了。对于这种情况在MSDN里面是这样处理的,我在这里贴出MSDN的原文: 如果您需要确定连接的当前状态,请进行非阻止、零字节的 Send 调用。如果该调用成功返回或引发 WAEWOULDBLOCK 错误代码 (10035),则该套接字仍然处于连接状态;否则,该套接字不再处于连接状态。 但是我在实际应用中发现,MSDN说的这种处理方法在很多时候根本无效,无法检测出网络已经异常断开了。那我们该怎么办呢? 我们知道,TCP有一个连接检测机制,就是如果在指定的时间内(一般为2个小时)没有数据传送,会给对端发送一个Keep-Alive数据报,使用的序列号是曾经发出的最后一个报文的最后一个字节的序列号,对端如果收到这个数据,回送一个TCP的ACK,确认这个字节已经收到,这样就知道此连接没有被断开。如果一段时间没有收到对方的响应,会进行重试,重试几次后,向对端发一个reset,然后将连接断掉。 在Windows中,第一次探测是在最后一次数据发送的两个小时,然后每隔1秒探测一次,一共探测5次,如果5次都没有收到回应的话,就会断开这个连接。但两个小时对于我们的项目来说显然太长了。我们必须缩短这个时间。那么我们该如何做呢?我要利用Socket类的IOControl()函数。我们来看看这个函数能干些什么: 使用 IOControlCode 枚举指定控制代码,为 Socket 设置低级操作模式。 如: 我们要搞清楚的就是inOptionValues的定义,在C++里它是一个结构体。我们来看看这个结构体: 在C#中,我们直接用一个Byte数组传递给函数: 具体实现代码: 首先,我们引入命名空间: using System.Runtime.InteropServices; 其次,构建方法: 好了,这样就成功了。
namespace System.Net.Sockets
{ public static class SocketExtensions { private const int BytesPerLong = 4; // 32 / 8 private const int BitsPerByte = 8; /// <summary> /// Sets the keep-alive interval for the socket. /// </summary> /// <param name="socket">The socket.</param> /// <param name="time">Time between two keep alive "pings".</param> /// <param name="interval">Time between two keep alive "pings" when first one fails.</param> /// <returns>If the keep alive infos were succefully modified.</returns> public static bool SetKeepAlive(this Socket socket,ulong time,ulong interval) { try { // Array to hold input values. var input = new[] { (time == 0 || interval == 0) ? 0UL : 1UL,// on or off time, interval }; // Pack input into byte struct. byte[] inValue = new byte[3 * BytesPerLong]; for (int i = 0; i < input.Length; i++) { inValue[i * BytesPerLong + 3] = (byte)(input[i] >> ((BytesPerLong - 1) * BitsPerByte) & 0xff); inValue[i * BytesPerLong + 2] = (byte)(input[i] >> ((BytesPerLong - 2) * BitsPerByte) & 0xff); inValue[i * BytesPerLong + 1] = (byte)(input[i] >> ((BytesPerLong - 3) * BitsPerByte) & 0xff); inValue[i * BytesPerLong + 0] = (byte)(input[i] >> ((BytesPerLong - 4) * BitsPerByte) & 0xff); } // Create bytestruct for result (bytes pending on server socket). byte[] outValue = BitConverter.GetBytes(0); // Write SIO_VALS to Socket IOControl. socket.SetSocketOption(SocketOptionLevel.Tcp,SocketOptionName.KeepAlive,true); socket.IOControl(IOControlCode.KeepAliveValues,inValue,outValue); } catch (SocketException e)
{
Console.WriteLine("Failed to set keep-alive: {0} {1}",e.ErrorCode,e); return false; } return true;
}
?
}
}
The result is not error,no exception and no keepalive in the expected time frame. I am passing both times in mill-seconds. The Trace that I have shows 12 bytes in the form of 01 00 00 00 10 27 00 00 98 3a 00 00 when called as SetKeepAlive(10000,15000); I am not really sure if I need to put the bytes in this order or not. If working directly with the Winsock API,the keepalive option uses a structure of 3 ULONGS with a 1 in the first one,the time in the 2nd one and the retry time (interval in this code) in the third one.
摘自:
https://blog.csdn.net/ma_jiang/article/details/7363195
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |