0

我如何为 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 会在这里工作吗?

4

1 回答 1

0

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

于 2013-09-03T06:59:03.520 回答