DotNetty使用之心跳机制

DotNetty使用之心跳机制因为 DotNetty 是从 java 的 Netty 框架仿写过来的 介绍的文档特别少 加之官方也没有提供 api 文档 所以之前一直不理解心跳的用法 最近忙里偷闲 稍稍研究了一番 终于有点明白了 现在将代码复制上来 留作日后查看 ps 精髓都在代码里 Uptime Client publicclassP conststringH 12

因为DotNetty是从java的Netty框架仿写过来的,介绍的文档特别少,加之官方也没有提供api文档,所以之前一直不理解心跳的用法。最近忙里偷闲,稍稍研究了一番,终于有点明白了。

现在将代码复制上来,留作日后查看(ps:精髓都在代码里):

Uptime.Client:

public class Program { const string HOST = "127.0.0.1"; const int PORT = 8045; // Sleep 5 seconds before a reconnection attempt. public const int RECONNECT_DELAY = 5; // Reconnect when the server sends nothing for 10 seconds. private const int READ_TIMEOUT = 10; private static UptimeClientHandler handler = new UptimeClientHandler(); private static Bootstrap bs = new Bootstrap(); static void Main(string[] args) { EventLoopGroup group = new EventLoopGroup(); bs.Group(group) .Channel<TcpSocketChannel>() .RemoteAddress(HOST, PORT) .Handler(new ActionChannelInitializer<ISocketChannel>(channel => { //IdleStateHandler心跳检测处理器,添加自定义处理Handler类实现userEventTriggered()方法作为超时事件的逻辑处理 //IdleStateHandler心跳检测每十秒进行一次读检测,如果十秒内ChannelRead()方法未被调用则触发一次userEventTrigger()方法. IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new IdleStateHandler(READ_TIMEOUT, 0, 0), handler);//第一个参数为读,第二个为写,第三个为读写全部 })); } }

Uptime.Client.UptimeClientHandler:

 public class UptimeClientHandler : SimpleChannelInboundHandler<object> { long startTime = -1; //ChannelActive:活跃状态,可接收和发送数据 public override void ChannelActive(IChannelHandlerContext ctx) { if (startTime < 0) { startTime = GetTimeStamp(); } Console.WriteLine("Connected to: " + ctx.Channel.RemoteAddress); } protected override void ChannelRead0(IChannelHandlerContext context, object message) { var byteBuffer = message as IByteBuffer; if (byteBuffer != null) { Console.WriteLine("Received from server: " + byteBuffer.ToString(Encoding.UTF8)); } context.WriteAsync(message); } public override void UserEventTriggered(IChannelHandlerContext ctx, object evt) { if (!(evt is IdleStateEvent)) { return; } IdleStateEvent e = evt as IdleStateEvent; if (e.State == IdleState.ReaderIdle) { // The connection was OK but there was no traffic for last period. Console.WriteLine("Disconnecting due to no inbound traffic"); ctx.CloseAsync(); } } //channelInactive: 处于非活跃状态,没有连接到远程主机。 public override void ChannelInactive(IChannelHandlerContext context) { Console.WriteLine("Disconnected from: " + context.Channel.RemoteAddress); } //channelUnregistered: 已创建但未注册到一个 EventLoop。 public override void ChannelUnregistered(IChannelHandlerContext context) { } public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Console.WriteLine("Exception: " + exception); context.CloseAsync(); } /// <summary> /// 获取时间戳 /// </summary> /// <returns></returns> private long GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds); } }

Uptime.Server:

class Program { private static readonly int PORT = 8045; private static readonly UptimeServerHandler handler = new UptimeServerHandler(); static void Main(string[] args) => RunServerAsync().Wait(); static async Task RunServerAsync() { IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1); IEventLoopGroup workerGroup = new MultithreadEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.Group(bossGroup, workerGroup) .Channel<TcpServerSocketChannel>() .Handler(new LoggingHandler("SRV-LSTN")) .ChildHandler(new ActionChannelInitializer<IChannel>(channel => { //工作线程连接器 是设置了一个管道,服务端主线程所有接收到的信息都会通过这个管道一层层往下传输 //同时所有出栈的消息也要这个管道的所有处理器进行一步步处理 IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast("Uptime", handler); })); // Bind and start to accept incoming connections. IChannel boundChannel = await b.BindAsync(PORT); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to gracefully // shut down your server. await boundChannel.CloseAsync(); } finally { await Task.WhenAll( bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)), workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))); } } }

Uptime.Server.UptimeServerHandler:

 public class UptimeServerHandler : SimpleChannelInboundHandler<object> { protected override void ChannelRead0(IChannelHandlerContext ctx, object msg) { // discard } //捕获 异常,并输出到控制台后断开链接,提示:客户端意外断开链接,也会触发 public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Console.WriteLine("Exception: " + exception); context.CloseAsync(); } }

最后,附上参考文档链接:DotNetty系列三:编码解码器,IdleStateHandler心跳机制,群发

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/232262.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • wcopy nfc pro智能读卡工具软件_手机NFC复制小区用的门禁卡[通俗易懂]

    wcopy nfc pro智能读卡工具软件_手机NFC复制小区用的门禁卡[通俗易懂]我们说一说目前的门禁卡到底有哪些类型呢?门禁卡一般分为:ID卡和IC卡。而EM卡、M1卡、CPU卡等等,都是这两种卡的细分。它们能够开门,都是基于RFID感应的原理来实现开门的。我们看一张图,在这张图中,能够看到一个数据名词,频率:ID卡的工作频率为125KHz频率,而IC卡的工作频率为13.56MHz,显然因为IC卡的频率高,所以,它的安全性比较高。小区基本上选择IC卡的概率会更高一…

    2022年5月22日
    330
  • 版图设计

    版图设计一、电路-版图-掩膜-光刻之间关系1.什么是版图集成电路制造工艺中,通过光刻和刻蚀将掩膜版上的图形转移到硅片上。这种制造集成电路时使用的掩膜版上的几何图形定义为集成电路的版图。集成电路制造厂

    2022年8月1日
    12
  • Java学习路线图(完整详细2021版)

    Java学习路线图(完整详细2021版)作为一个男人我感觉必须得做点什么来证明一下自己,现在我又回来了,准备把自己的节操准备补一下 另外给各位未来的Java程序员说一句,别的我不清楚,学习编程请从一而终 咱们学习编程就挺难的,有这些先驱者来带领咱们学习,咱们应该感激,而且最重要的事跟着你选定的一家一直学下去 因为每家学校的学习大纲都是不一样的,但是程序员其实都是一样的,这句话你细品!仔细的品! 我不希望你忙忙碌碌的整理那么多东西,挑肥拣瘦的,最后自己学的东西还是缺失的,要不就…

    2022年5月17日
    85
  • mapreduce-shuffling

    mapreduce-shufflingmap->reducemap和reduce之间的过程,成为shuffling,官方图是这样介绍的.(这样描述不是很准确)MapTask每个map任务都有一个环形内存缓冲区用于存储任务的输出.默认100MB(MRJobConfig.IO_SORT_MB修改)一旦缓冲达到阈值(MRJobConfig.MAP_SORT_SPILL_PERCENT)0.8,后台

    2025年6月26日
    3
  • JSON字符串转对象_微信小程序配置文件

    JSON字符串转对象_微信小程序配置文件微信就是最大的坑!!!!!之前做的小程序,前台都是默认参数(返回json之类的),使用也都正常然而,今天发现的问题也是愁死个人,返回的json就是字符串,自然取不到里面的数据.小程序的js还有好多函数他不支持,坑.之前都是returnjson_encode($arr);这样子返回数据,代码都是一样,就这次莫名不好使.网上的答案也是千篇一律.最后有两篇文章都提到了一个问题,一试,果然有效.转jso…

    2022年9月28日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号