什么是保活定时器以及如何实现它
本文关键字:何实现 实现 定时器 什么 | 更新日期: 2023-09-27 18:29:55
如何为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会在这里工作吗?
您可以使用SO_KEEPLIVE选项将TCP Keepalive行为添加到套接字中。基本上,如果另一端(对等端)死了,那么套接字将发送一列keepalive(我认为是3),如果对等端没有响应(如果它死了,它不会响应),那么套接字会关闭连接并释放与连接相关的资源。