在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 设置低级操作模式。
命名空间:System.Net.Sockets
程序集:System(在 system.dll 中)
语法
C#
public int IOControl (
IOControlCode ioControlCode,
byte[] optionInValue,
byte[] optionOutValue
)
参数
ioControlCode
一个 IOControlCode 值,它指定要执行的操作的控制代码。
optionInValue
Byte 类型的数组,包含操作要求的输入数据。
optionOutValue
Byte 类型的数组,包含由操作返回的输出数据。
返回值
optionOutValue 参数中的字节数。
如:
 socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);我们要搞清楚的就是inOptionValues的定义,在C++里它是一个结构体。我们来看看这个结构体:
 struct tcp_keepalive
struct tcp_keepalive  {
{  u_long  onoff; //是否启用Keep-Alive
    u_long  onoff; //是否启用Keep-Alive u_long  keepalivetime; //多长时间后开始第一次探测(单位:毫秒)
    u_long  keepalivetime; //多长时间后开始第一次探测(单位:毫秒) u_long  keepaliveinterval; //探测时间间隔(单位:毫秒)
    u_long  keepaliveinterval; //探测时间间隔(单位:毫秒) };
}; 
在C#中,我们直接用一个Byte数组传递给函数:
 uint dummy = 0;
uint dummy = 0; byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3]; BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);//是否启用Keep-Alive
BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);//是否启用Keep-Alive BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));//多长时间开始第一次探测
BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));//多长时间开始第一次探测 BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);//探测时间间隔
BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);//探测时间间隔
具体实现代码:
首先,我们引入命名空间:
using System.Runtime.InteropServices;
其次,构建方法:
 public static void AcceptThread()
        public static void AcceptThread() {
        { Thread.CurrentThread.IsBackground = true;
            Thread.CurrentThread.IsBackground = true; while (true)
            while (true) {
            { uint dummy = 0;
                uint dummy = 0; byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
                byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3]; BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
                BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0); BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
                BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy)); BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
                BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2); try
                try {
                { Accept(inOptionValues);
                    Accept(inOptionValues); }
                } catch { }
                catch { } }
            } }
        }
 private static void Accept(byte[] inOptionValues)
        private static void Accept(byte[] inOptionValues) {
        { Socket socket = Public.s_socketHandler.Accept();
            Socket socket = Public.s_socketHandler.Accept(); socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
            socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); UserInfo info = new UserInfo();
            UserInfo info = new UserInfo(); info.socket = socket;
            info.socket = socket; int id = GetUserId();
            int id = GetUserId(); info.Index = id;
            info.Index = id; Public.s_userList.Add(id, info);
            Public.s_userList.Add(id, info); socket.BeginReceive(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), info);
            socket.BeginReceive(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), info); }
        }
好了,这样就成功了。
{
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 WinsockAPI, 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://www.cnblogs.com/chenhuadan/p/11615704.html
