什么是在.NET中保持活动套接字检查的最佳方法?

11 .net sockets

我正在寻找一种在.NET中进行保持活动检查的方法.该方案适用于UDP和TCP.

目前在TCP中,我所做的是一方连接,当没有数据要发送时,它每隔X秒发送一次保持活动.

我希望对方检查数据,如果在X秒内收到非数据,则提出事件左右.

我尝试做的一种方法是进行阻塞接收并将套接字的RecieveTimeout设置为X秒.但问题是每当Timeout发生时,套接字的Receive会抛出一个SocketExeception并且这边的套接字会关闭,这是正确的行为吗?为什么套接字在超时后关闭/死亡而不是仅仅继续?

检查是否有数据和睡眠是不可接受的(因为我可能在睡觉时接收数据时滞后).

那么最好的方法是什么呢?为什么我在另一方面描述的方法失败了?

Gre*_*ean 19

如果您的字面意思是"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);
    }
Run Code Online (Sandbox Code Playgroud)

  • 我很乐意回复那些试图以这种方式帮助你的人. (8认同)
  • 我想知道你是否读过这个问题:)当然我不是 (3认同)

TTo*_*oni 0

由于您无法使用阻塞(同步)接收,因此您将不得不接受异步处理。幸运的是,使用 .NET 可以很容易地做到这一点。查找 BeginReceive() 和 EndReceive() 的描述。或者查看这篇文章这个

至于超时行为我没有发现对此有结论性的描述。由于它没有记录在案,因此您必须假设这是预期的行为。