c# – Tcp连接保持活动状态

我正在创建一个客户端服务器应用程服务器已经设计好并等待客户端的连接.现在,在客户端部分,我希望在应用程序的整个生命周期中保持连接活动,并且只有在主客户端应用程序关闭或关闭或服务器关闭时才会关闭连接.

目前每10秒服务器关闭TCP连接.我尝试过

socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);

但它对我不起作用..
下面是我的代码块

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

在我有的处理程序中:

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
            /* when there is no datapacket  means no TCP connection is alive now (how can i keep Tcp alive here) */
        }
    }
}
最佳答案
在对SetSocketOption()的调用中,KeepAlive在SocketOptionLevel.Tcp级别无效,而是使用SocketOptionLevel.Socket.

SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.KeepAlive,true);

转载注明原文:c# – Tcp连接保持活动状态 - 代码日志