根据这里的一些帖子,我编写了以下简单的方法来设置我的套接字 KeepAlive,并且它似乎有效。在拔掉以太网电缆以断开两个服务之间的连接后,我的网络库可以处理 SocketAsyncEventArgs Completed 事件上的 0 字节传输并启动 Disconnected 事件。
但由于某种原因,我需要使用百分之一秒而不是毫秒。我能找到的所有相关文档似乎都表明我应该使用毫秒。
(编辑)我现在已经验证返回的字节与其他两种方法匹配:
http://www.codeproject.com/Articles/117557/Set-Keep-Alive-Values
(编辑)我也对此进行了 WireSharked,并且可以验证当间隔设置为 500 时,KeepAlives 每 5 秒就会发出一次。
什么给了???最新版本的 .NET 中有什么问题吗?
private static byte[] GetKeepAliveOption(bool isEnabled, int keepAliveTime, int keepAliveInterval)
{
//time and interval are in hundredths of a second to work properly
//12 keepalive bytes, 1st 4 for enabled, next 4 for time, next 4 for interval
byte[] bytes = new byte[12];
if (isEnabled)
{
bytes[0] = 1;
}
byte[] keepAliveTimeBytes = BitConverter.GetBytes(KeepAliveTime);
Buffer.BlockCopy(keepAliveTimeBytes, 0, bytes, 4, 4);
byte[] keepAliveIntervalBytes = BitConverter.GetBytes(KeepAliveInterval);
Buffer.BlockCopy(keepAliveIntervalBytes, 0, bytes, 8, 4);
return bytes;
}
最佳答案
在评论中回答了我自己的问题。抱歉,这是我的第一篇文章,我应该在这样的答案中这样做。
其要点是了解参数:
KeepAliveTime是发送KeepAlive消息的时间间隔。
KeepAliveInterval 是当初始 KeepAlive 消息尚未被确认时发送重传探测之间的时间间隔。
关于c# - 套接字保持事件单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17958232/