C# Socket开启TCP Keep-Alive数据包

                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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值