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