转载自:http://zch7811.blog.163.com/blog/static/177052282011224351928/
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 参数中的字节数。
C#中设置KeepAlive的代码
uint dummy = 0;
byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)15000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
BitConverter.GetBytes((uint)15000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
IPEndPoint iep = new IPEndPoint(this._IPadd, xxxx);
this._socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this._socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
this._socket.Connect(iep);
这里我设定TCP15秒钟空闲,就开始发送KeepAlive包,其实完全可是设定得长一点。
#region 检测网络状态
[DllImport("sensapi.dll")]
private extern static bool IsNetworkAlive(out int connectionDescription);
private void NetCheckThread()
{
while (true)
{
int flags;//上网方式
bool m_bOnline = true;//是否在线
m_bOnline = IsNetworkAlive(out flags);
if (m_bOnline)
{
if (!NetAlive)
{
NetAlive = true;
try
{
if (NetConnect != null) NetConnect(this, null);
}
catch { }
}
}
else
{
if (NetAlive)
{
NetAlive = false;
try
{
if (NetDisconnect != null) NetDisconnect(this, null);
}
catch { }
}
}
Thread.Sleep(1);
}
}
#endregion
public static void AcceptThread()
...{
Thread.CurrentThread.IsBackground = true;
while (true)
...{
uint dummy = 0;
byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
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) * 2);
try
...{
Accept(inOptionValues);
}
catch ...{ }
}
}
private static void Accept(byte[] inOptionValues)
...{
Socket socket = Public.s_socketHandler.Accept();
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
UserInfo info = new UserInfo();
info.socket = socket;
int id = GetUserId();
info.Index = id;
Public.s_userList.Add(id, info);
socket.BeginReceive(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), info);
}
参考:
http://www.360doc.com/content/12/0809/10/10543686_229170807.shtml
浙公网安备 33010602011771号