首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

TCP同步通信,心跳包如何具体实现

2013-04-07 
TCP同步通信,心跳包怎么具体实现啊TCP同步通信,心跳包怎么具体实现啊求能详细点的啊[解决办法]最好的办法

TCP同步通信,心跳包怎么具体实现啊
TCP同步通信,心跳包怎么具体实现啊
求能详细点的啊 
[解决办法]
最好的办法是把它封装一下,然后在客户端和服务器端调用的时候都设置就行。


    public static class SocketExtensions
    {
        //found at http://www.extensionmethod.net/Details.aspx?ID=271, slightly modified
        /// <summary>
        /// Using IOControl code to configue socket KeepAliveValues for line disconnection detection(because default is toooo slow) 
        /// </summary>
        /// <param name="instance">A socket instance</param>
        /// <param name="KeepAliveTime">The keep alive time. (ms)</param>
        /// <param name="KeepAliveInterval">The keep alive interval. (ms)</param>
        public static void SetSocketKeepAliveValues(this Socket instance, int KeepAliveTime, int KeepAliveInterval)
        {
            //KeepAliveTime: default value is 2hr
            //KeepAliveInterval: default value is 1s and Detect 5 times

            //the native structure
            //struct tcp_keepalive {
            //ULONG onoff;
            //ULONG keepalivetime;
            //ULONG keepaliveinterval;
            //};

            uint dummy = 0; //lenth = 4
            int length = Marshal.SizeOf(dummy);
            byte[] inOptionValues = new byte[length * 3]; //size = lenth * 3 = 12
            bool OnOff = true;

            BitConverter.GetBytes((uint)(OnOff ? 1 : 0)).CopyTo(inOptionValues, 0);
            BitConverter.GetBytes((uint)KeepAliveTime).CopyTo(inOptionValues, length);
            BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo(inOptionValues, length * 2);
            // of course there are other ways to marshal up this byte array, this is just one way
            // call WSAIoctl via IOControl



            // .net 1.1 type
            //int SIO_KEEPALIVE_VALS = -1744830460; //(or 0x98000004)
            //socket.IOControl(SIO_KEEPALIVE_VALS, inOptionValues, null); 

            // .net 3.5 type
            instance.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
        }
    }


[解决办法]
服务器端

                socketClient.Connect(ServerIP, ServerPort);
                socketClient.SetSocketKeepAliveValues(ConstTools.KeepAliveTime, ConstTools.KeepAliveInterval); 

客户端

                var socketClient = socketServer.EndAccept(ar);
                socketClient.SetSocketKeepAliveValues(ConstTools.KeepAliveTime, ConstTools.KeepAliveInterval);

设置后,不管关哪边,另外一边都有异常。

热点排行