什么是保持活动计时器以及如何实现它

时间:2013-09-03 06:55:11

标签: c# tcp keep-alive

如何为TCP连接实现Keep alive计时器.. 我的服务器每3秒关闭一次TCP。因此,服务器没有收到其他数据。 我可以通过以下方式保持这种联系: -

1. Sending some data continusly with that 3 seconds.(my requirment is not suitable with this).
2. can i use  TCP keep alive here?. does TCP keep alive means that TCP connection would be there even if server closes it?

这是我的代码

   public TCPStreamDevice(string RemoteIPAddress, int RemotePort, string SourceIPAddress, int SourcePortNo)


        {
                mIpAddress = RemoteIPAddress;
                mPort = RemotePort;

                mClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                System.Net.IPEndPoint LocalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(SourceIPAddress), SourcePortNo);

                               mClient.Bind(LocalEndPoint);

                mDataReceivedCallback = new AsyncCallback(DataReceivedTCPCallback_Handler);
                mBuffer = new byte[1024];
                Description = new DeviceDescription();
            }

and in handler i have ..





     private void DataReceivedTCPCallback_Handler(IAsyncResult ar)
                {
                    try
                    {
                        Socket client = (Socket)ar.AsyncState;
                        int bytesReceived = client.EndReceive(ar);

                        if (bytesReceived > 0)
                        {
                          to know transport level errors
                            //EngineInterface.reponseReceived(mBuffer, false);

                            ReceiveCallBackFunc(mBuffer, bytesReceived);

                            client.BeginReceive(mBuffer, 0, 1024, SocketFlags.None, DataReceivedTCPCallback_Handler, client);
                        }
                        else
                        {
    //disconnect   
    /* whrn there is no datapacket  means no TCP connection is alive now(how can i keep tCp alive here) */

    }

我想继续与服务器通信(虽然服务器已关闭连接)。所以我需要重新启动TCP连接或KEEP ALIVE可以在这里工作吗?

1 个答案:

答案 0 :(得分:0)

您可以使用SO_KEEPLIVE选项将TCP Keepalive行为添加到套接字。基本上,如果另一端(对等体)死亡,那么套接字将发送一系列keepalive(我认为3)并且如果hte peer没有响应(它不会响应,如果它死了),那么套接字将关闭连接并释放与teh conneciton相关的资源。