我正在寻找一种方法来做一个保持连接检查在.NET。场景是为UDP和TCP。
目前在TCP中,我所做的是一端连接,当没有数据要发送时,它每X秒发送一次keep alive。
我希望另一端检查数据,如果在X秒内未收到数据,则引发一个事件。
我尝试的一种方法是执行阻塞接收,并将套接字的RecieveTimeout设置为X秒。但问题是,每当超时发生时,套接字的接收都会抛出SocketExeception,而这一端的套接字将关闭,这是正确的行为吗?为什么套接字在超时后关闭/终止,而不是继续运行?
检查是否有数据和睡眠是不可接受的(因为我可能在睡眠时延迟接收数据)。
那么,最好的方法是什么,为什么我在另一边描述的方法失败了?
发布于 2008-10-05 01:52:13
如果您的字面意思是"KeepAlive",请尝试以下方法。
public static void SetTcpKeepAlive(Socket socket, uint keepaliveTime, uint keepaliveInterval)
{
/* the native structure
struct tcp_keepalive {
ULONG onoff;
ULONG keepalivetime;
ULONG keepaliveinterval;
};
*/
// marshal the equivalent of the native structure into a byte array
uint dummy = 0;
byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
BitConverter.GetBytes((uint)(keepaliveTime)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)keepaliveTime).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
BitConverter.GetBytes((uint)keepaliveInterval).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
// write SIO_VALS to Socket IOControl
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
请注意,时间单位为毫秒。
发布于 2021-10-08 13:54:22
如果你有一个tcp服务器,它只是以不规则的时间间隔写入数据,而你想让alive在后台运行:
tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 1);
tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 2);
tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 2);
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
如果服务器不(通常是自动)回复tcp keep alives,将导致异步读取抛出超时异常。
https://stackoverflow.com/questions/169170
复制相似问题