c# - 套接字保持事件单元

标签 c# visual-studio-2012

根据这里的一些帖子,我编写了以下简单的方法来设置我的套接字 KeepAlive,并且它似乎有效。在拔掉以太网电缆以断开两个服务之间的连接后,我的网络库可以处理 SocketAsyncEventArgs Completed 事件上的 0 字节传输并启动 Disconnected 事件。

但由于某种原因,我需要使用百分之一秒而不是毫秒。我能找到的所有相关文档似乎都表明我应该使用毫秒。

(编辑)我现在已经验证返回的字节与其他两种方法匹配:

http://www.codeproject.com/Articles/117557/Set-Keep-Alive-Values

http://social.msdn.microsoft.com/Forums/en-US/35dfb50e-1e14-40c1-af01-f359be4d6a02/how-to-set-socket-keep-alive-timeinterval-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/

相关文章:

c# - 在 Visual Studio 内访问 Microsoft Azure

c# - Entity Framework 多对多不填充集合

c# - 设计 : Queue Management question (C#)

c#登录表单出现Mysql错误

c# - 删除老式的终结器

javascript - TypeScript编译错误 "Unknown file Extension"

c# - 如何在 Windows Mobile 中支持不同的屏幕尺寸?

entity-framework - Visual Studio 2012 最终版不兼容

VB.NET For each 枚举不正确

c# - UserControl 在 Visual Studio 设计器中显示属性,但属性未更改