Socket sc = new Socket(SocketType.Stream, ProtocolType.Tcp);
ep = new IPEndPoint(IPAddress.Parse(IP), Port);
// 2. 启用系统级Keep-Alive(需Windows/Linux支持)
sc.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
// 配置Keep-Alive参数
//结构体描述:
//- 第一个4字节整数表示启用了KeepAlive之后,首次发送KeepAlive包的时间,单位毫秒。
//- 第二个4字节整数表示如果第一次KeepAlive探测没有收到响应,那么程序等待再发送探测的时间间隔,单位毫秒。
//- 第三个4字节整数表示连续收到探测失败的次数,达到这个次数后对端将被认定为不可达。
uint dummy = 0;
byte[] inOptionValues = new byte[12] { 0,0,0,0,0,0,0,0,0,0,0,0}; // 12 bytes total
// 启用KeepAlive
BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
// 开始首次KeepAlive探测前的闲置时间(比如:5000ms)
BitConverter.GetBytes((uint)1000).CopyTo(inOptionValues, 4);
// KeepAlive探测之间的时间间隔(比如:1000ms)
BitConverter.GetBytes((uint)1000).CopyTo(inOptionValues, 8);
// 设置KeepAlive选项
sc.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
sc.Connect(ep);