C# Socket 长连接设置Keepalive

首先TCP 底层自带KeepAlive 连接监测机制,通常在指定时间:keepalivetime(毫秒)内没有数据交互,则按keepaliveinterval(毫秒)设定重复发送keep-alive包,并且重复次数达到设置值或系统默认值,例如win10系统为10次,如果都没有回应,则视为客户端异常或网络中断,表现为TCP底层发送Reset 指令,连接断开。

实验如下:

首先更改开启KeepAlive ,并且设置首次没有数据交互发探测包的间隔为5s, 探测间隔为1s: C# 版本如下:

        #region 连接
        /// <summary>
        /// 异步连接
        /// </summary>
        /// <param name="ip">要连接的服务器的ip地址</param>
        /// <param name="port">要连接的服务器的端口</param>
        public void ConnectAsync(string ip, int port)
        {
            IPAddress ipAddress = null;
            try
            {
                ipAddress = IPAddress.Parse(ip);
            }
            catch (Exception)
            {
                throw new Exception("ip地址格式不正确,请使用正确的ip地址!");
            }
            try
            {
                if (!tcpClient.Connected)
                {
                    tcpClient.BeginConnect(ipAddress, port, ConnectCallBack, tcpClient);
                }
                else if (isStopWork)
                {
                    isStopWork = false;
                    OnComplete(tcpClient, SocketAction.Connect);
                }
            }
            catch
            {
            }            
        }

        /// <summary>
        /// 异步连接的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void ConnectCallBack(IAsyncResult ar)
        {
            try
            {
                TcpClient client = ar.AsyncState as TcpClient;
                client.EndConnect(ar);
                uint dummy = 0;
                byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
                BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);//启用Keep-Alive
                BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));//在这个时间间隔内没有数据交互,则发探测包 毫秒
                BitConverter.GetBytes((uint)1000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);//发探测包时间间隔 毫秒
                client.Client.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
                OnComplete(client, SocketAction.Connect);
            }
            catch(Exception ex)
            {
                
            }           
        }
        #endregion

利用wireshark抓包如下:

接下来测试KeepAlive断开:正常TCP建立连接 后,拔掉网线:重新抓包如下图所示:

由上图可以看到在每5秒发keepalive探测包后,由于拔掉网线,140(客户端)给151(服务器端)发了连续10个keepalive探测重试包,时间间隔为1s; 10次后,最终导致TCP指令RST (reset)发出,标识连接异常断开。

启用KeepAlive机制后,对于TCP因为物理链路上断开的连接,可以更快的感知发现。正常情形下TCP连接双方建立连接后,即使物理层链路断开,例如拔掉网线等,TCP连接仍视为正常连接,此时重新插回网线,仍然可以正常的收发数据,好像网线拔掉从未发生过一样。在拔掉网线后,读和写会有什么影响呢?如果是write, socket 是可以正常返回的,因为write只保证发送到本地缓冲区,直至内核发现对方不可达。同样道理网线拔除后读也回有一个超时感知时间(和SendTimeOut或ReceiveTimeOut无关),C#中会引发SocketExcetion。

发布了92 篇原创文章 · 获赞 55 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/elie_yang/article/details/95197181
今日推荐