什么是做永葆插座检查.NET最好的方法是什么?
我要寻找一个方式做一个永葆检查在.NET。该方案是UDP和TCP。
I am looking for a way to do a keep alive check in .NET. The scenario is for both UDP and TCP.
目前在TCP是我做的是,一边连接,当没有数据发送它发送一个永葆每X秒。
Currently in TCP what I do is that one side connects and when there is no data to send it sends a keep alive every X seconds.
我希望对方来检查数据,如果收到秒钟后非,引发一个事件左右。
I want the other side to check for data, and if non was received in X seconds, to raise an event or so.
我试图做一个办法就是做一个阻塞接收和设置套接字的RecieveTimeout以X秒。但问题是每当发生超时,套接字的接收会引发SocketExeception,并在这一侧的接口将关闭,这是正确的行为?为何套接字关闭/死只是去上的超时之后呢?
One way i tried to do was do a blocking receive and set the socket's RecieveTimeout to X seconds. But the problem was whenever the Timeout happened, the socket's Receive would throw an SocketExeception and the socket on this side would close, is this the correct behaviour ? why does the socket close/die after the timeout instead of just going on ?
一个检查,如果有数据和睡眠是不能接受的(因为我可能会落后于接收数据,同时睡觉)。
A check if there is data and sleep isn't acceptable (since I might be lagging on receiving data while sleeping).
那么,什么是去了解这一点的最好办法,为什么是我所描述的另一边失败?
So what is the best way to go about this, and why is the method i described on the other side failing ?
如果你从字面上的意思是的KeepAlive,请尝试以下。
If you literally mean "KeepAlive", try the following.
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);
}