TCP连接保持活动 [英] Tcp connection Keep alive

查看:72
本文介绍了TCP连接保持活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i am creating a client server application. the server is already design and in place waiting for connection from the client. Now in the client section i would like to keep the connection alive throughout th life of the application and the connection only closes when the main client application close's or shutdown or the server closes it.

当前每隔10秒,服务器就会关闭TCP连接.我尝试使用

Currently every 10 seconds Server closes the TCP connection.I tried with

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

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

but it doesn't work for me.. Below is my code block

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 .

In the call to SetSocketOption(), KeepAlive is not valid at the SocketOptionLevel.Tcp level, instead use SocketOptionLevel.Socket.

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

这篇关于TCP连接保持活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆