gpt4 book ai didi

.net - 在 .NET 中进行保持事件套接字检查的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-02 22:11:08 35 4
gpt4 key购买 nike

我正在寻找一种在 .NET 中进行保持事件检查的方法。该场景适用于 UDP 和 TCP。

目前在 TCP 中,我所做的是一侧连接,当没有数据要发送时,它每 X 秒发送一次保持事件状态。

我希望对方检查数据,如果在 X 秒内未收到数据,则引发事件等。

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

检查是否有数据和 sleep 是 Not Acceptable (因为我在 sleep 时接收数据可能会滞后)。

那么解决这个问题的最佳方法是什么,为什么我在另一边描述的方法失败了?

最佳答案

如果您的字面意思是“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);
}

请注意时间单位为毫秒。

关于.net - 在 .NET 中进行保持事件套接字检查的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/169170/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com