Netty教程07:心跳检测机制
需求:编写一个 Netty心跳检测机制案例, 当服务器超过3秒没有读时,就提示读空闲
当服务器超过5秒没有写操作时,就提示写空闲
实现当服务器超过7秒没有读或者写操作时,就提示读写空闲
Server
package com.lian.heartbeat;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;import java.util.concurrent.TimeUnit;public class Server {public static void main(String[] args) throws InterruptedException {NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);NioEventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();ChannelFuture channelFuture = serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();//加入一个netty 提供 IdleStateHandler/*说明1. IdleStateHandler 是netty 提供的处理空闲状态的处理器2. long readerIdleTime : 表示多长时间没有读, 就会发送一个心跳检测包检测是否连接3. long writerIdleTime : 表示多长时间没有写, 就会发送一个心跳检测包检测是否连接4. long allIdleTime : 表示多长时间没有读写, 就会发送一个心跳检测包检测是否连接5. 文档说明triggers an {@link IdleStateEvent} when a {@link Channel} has not performed* read, write, or both operation for a while.6. 当 IdleStateEvent 触发后 , 就会传递给管道 的下一个handler去处理通过调用(触发)下一个handler 的 userEventTiggered , 在该方法中去处理 IdleStateEvent(读空闲,写空闲,读写空闲)*/pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));//加入一个对空闲检测进一步处理的handler(自定义)pipeline.addLast(new MyServerHandler());}}).bind(9999).sync();//监听关闭通道channelFuture.channel().closeFuture().sync();}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}
ServerHandler
package com.lian.heartbeat;import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;public class MyServerHandler extends SimpleChannelInboundHandler<String> {/**** @param ctx 上下文* @param evt 事件* @throws Exception*/@Overridepublic void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {Channel channel = ctx.channel();if (evt instanceof IdleStateEvent){IdleStateEvent idleStateEvent = (IdleStateEvent) evt;String eventType = null;switch (idleStateEvent.state()){case READER_IDLE:eventType = "read idle";break;case WRITER_IDLE:eventType = "write idle";break;case ALL_IDLE:eventType = "all idle";break;}System.out.println(channel.remoteAddress()+"time out event"+eventType);System.out.println("server deal...");//如果发生空闲,我们关闭通道//ctx.channel().close();}}@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {}}
Client
package com.lian.groupprivatechat;import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;import java.util.Scanner;public class Client {private final String host;private final Integer port;public Client(String host, Integer port) {this.host = host;this.port = port;}public void run() throws Exception {NioEventLoopGroup clientEventLoopGroup = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(clientEventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("decoder",new StringDecoder());pipeline.addLast("encoder",new StringEncoder());pipeline.addLast(new ClientHandler());}});//绑定主机和端口ChannelFuture channelFuture = bootstrap.connect(host,port).sync();//添加监听器channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {@Overridepublic void operationComplete(Future<? super Void> future) throws Exception {if (channelFuture.isSuccess()){System.out.println("client is startting...");}else if (channelFuture.isDone()){System.out.println("client is start success...");}}});Channel channel = channelFuture.channel();System.out.println("----------"+channel.localAddress()+"-----------");//创建扫描器Scanner scanner = new Scanner(System.in);while (scanner.hasNextLine()){String msg = scanner.nextLine();//将控制台上的数据写入到channel中channel.writeAndFlush(msg+"\r\n");}//监听关闭通道channelFuture.channel().closeFuture().sync();scanner.close();}finally {clientEventLoopGroup.shutdownGracefully();}}public static void main(String[] args) throws Exception {new Client("127.0.0.1",9999).run();}
}
ClientHandler
package com.lian.groupprivatechat;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;public class ClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {System.out.println(msg.trim());}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.channel().close();}
}
测试
127.0.0.1:3570time out eventread idle
server deal...
/127.0.0.1:3570time out eventwrite idle
server deal...
/127.0.0.1:3570time out eventread idle
server deal...
/127.0.0.1:3570time out eventall idle
server deal...
/127.0.0.1:3570time out eventread idle
server deal...
/127.0.0.1:3570time out eventwrite idle
...
Netty教程07:心跳检测机制相关推荐
- netty 中的心跳检测机制
为什么要心跳检测机制 当服务端接收到客户端的连接以后,与客户端建立 NioSocketChannel 数据传输的双工通道,但是如果连接建立以后,客户端一直不给服务端发送消息,这种情况下是占用了资源,属 ...
- Netty(八) Netty心跳检测机制
1.什么是长链接和短链接 在HTTP/1.0中默认使用短连接.也就是说,客户端和服务器每进行一次HTTP操作,就建立一次连接,任务结束就中断连接.当客户端浏览器访问的某个HTML或其他类型的Web页中 ...
- Netty心跳检测机制
一.Netty心跳检测机制 心跳:即在 TCP 长连接中,客户端和服务器之间定期发送的一种特殊的数据包,通知对方自己还在线,以确保 TCP 连接的有效性. 在 Netty 中,实现心跳机制的关键是 I ...
- netty的编解码、粘包拆包问题、心跳检测机制原理
文章目录 1. 编码解码器 2. 编解码序列化机制的性能优化 3. Netty粘包拆包 4. Netty心跳检测机制 5. Netty断线自动重连实现 1. 编码解码器 当你通过netty发送或者接受 ...
- Netty空闲心跳检测机制
概述 Netty提供了一个读写空闲心跳检测机制的Handler,用于检测读空闲.写空闲.读写空闲. 如果服务端在一定时间内没有执行读请求,就会触发读空闲事件,一定时间内没有执行写请求,就会触发写空闲事 ...
- Netty -Netty心跳检测机制案例,Netty通过WebSocket编程实现服务器和客户端长链接
Netty心跳检测机制案例 案例要求 编写一个Netty心跳检测机制案例,当服务器超过3秒没有读时,就提示读空闲 当服务器超过5秒没有写操作时,提示写空闲 服务器超过7秒没有读或者写操作时,就提示读写 ...
- Netty学习(七):心跳检测机制
一.什么是心跳检测机制 所谓心跳, 即在 TCP 长连接中, 客户端和服务器之间定期发送的一种特殊的数据包, 通知对方自己还在线, 以确保 TCP 连接的有效性. 心跳机制主要是客户端和服务端长时间连 ...
- Netty 心跳检测机制
心跳检测机制 目的:就是用于检测 检测通信对方是否还"在线",如果已经断开,就要释放资源 或者 尝试重连. 大概的实现原理就是:在服务器和客户端之间一定时间内没有数据交互时, 即处 ...
- netty自定义消息实现心跳检测与重连
netty的心跳发送的重连,主要在client端.前面有关于自定义协议的demo:https://blog.csdn.net/zc_ad/article/details/83829620 其实客户端心 ...
最新文章
- AI 技术实力图谱全解析!2018 中国 AI 开发者大会重磅来袭
- JavaScript性能优化【下】--性能优化的具体方式
- 怎么看b树是几阶_数据库原理基础:设计B树与B+树的目的以及二者的优劣
- 初者Python笔记(案例:用字典无限添加节点)
- python中自定义超时异常的几种方法
- 1.4.1bat脚本命令COPY 拷贝 复制到
- DNS域名解析基础知识
- 2021-06-29初识JQuery
- 18.ARP报文格式详解
- 网络硬件三剑客的集线器(Hub)、交换机(Switch)与路由器(Router)
- 计算机操作系统-运行机制、体系结构
- Unity设置和显示FPS
- 【汇正财经】股票上市交易的费用都有哪些?
- 苹果官方付费升级内存_趁双十一大促销,赶紧升级苹果一体机升级SSD固态和液态内存吧...
- 我想给宝宝开发育儿软件
- Django 对符合条件的字段求和 aggregate
- 两段视频如何无缝拼接?如何将两个视频拼接在一起
- 多个公网服务器搭建k8s集群
- 新手利用C# 实现简单仿QQ登陆注册功能
- Java学习之路(书籍推荐)