我是靠谱客的博主 谦让高跟鞋,这篇文章主要介绍Netty学习----Netty 编解码器和 handler 的调用机制一. Netty 编解码器和 handler 的调用机制二. 编码解码器三. 解码器-ByteToMessageDecoder四. Netty 的 handler 链的调用机制五. 解码器-ReplayingDecoder六. 其它解码器六. 其它编码器七. Log4j 整合到 Netty,现在分享给大家,希望可以做个参考。
Netty 编解码器和 handler 的调用机制
- 一. Netty 编解码器和 handler 的调用机制
- 二. 编码解码器
- 三. 解码器-ByteToMessageDecoder
- 四. Netty 的 handler 链的调用机制
- 五. 解码器-ReplayingDecoder
- 六. 其它解码器
- 六. 其它编码器
- 七. Log4j 整合到 Netty
一. Netty 编解码器和 handler 的调用机制
- netty 的组件设计:Netty 的主要组件有 Channel、EventLoop、ChannelFuture、ChannelHandler、ChannelPipe 等
- ChannelHandler 充当了处理入站和出站数据的应用程序逻辑的容器。例如,实现 ChannelInboundHandler 接口(或ChannelInboundHandlerAdapter),你就可以接收入站事件和数据,这些数据会被业务逻辑处理。当要给客户端发 送 响 应 时 , 也 可 以 从 ChannelInboundHandler 冲 刷 数 据 。 业 务 逻 辑 通 常 写 在 一 个 或 者 多 个
ChannelInboundHandler 中。ChannelOutboundHandler 原理一样,只不过它是用来处理出站数据的 - ChannelPipeline 提供了 ChannelHandler 链的容器。以客户端应用程序为例,如果事件的运动方向是从客户端到服务端的,那么我们称这些事件为出站的,即客户端发送给服务端的数据会通过 pipeline 中的一系列ChannelOutboundHandler,并被这些 Handler 处理,反之则称为入站的
二. 编码解码器
- 当 Netty 发送或者接受一个消息的时候,就将会发生一次数据转换。入站消息会被解码:从字节转换为另一种格式(比如 java 对象);如果是出站消息,它会被编码成字节。
- Netty 提供一系列实用的编解码器,他们都实现了 ChannelInboundHadnler 或者 ChannelOutboundHandler 接口。在这些类中,channelRead 方法已经被重写了。以入站为例,对于每个从入站 Channel 读取的消息,这个方法会被调用。随后,它将调用由解码器所提供的 decode()方法进行解码,并将已经解码的字节转发给 ChannelPipeline中的下一个 ChannelInboundHandler。
三. 解码器-ByteToMessageDecoder
-
类继承图
-
由于不可能知道远程节点是否会一次性发送一个完整的信息,tcp 有可能出现粘包拆包的问题,这个类会对入站数据进行缓冲,直到它准备好被处理.
3)ByteToMessageDecoder 实例分析
- 每次入站从ByteBuf中读取8字节,将其解码为一个int,将它添加到下一个List中。当没有更多元素可以被添加到该List中时,它的内容将会被发送给下一个ChannelInboundHandler。
- Int在被添加到List中时,会被自动装箱为Integer,在调用readInt()方法前必须验证所输入的ByteBuf是否具有足够的数据。
四. Netty 的 handler 链的调用机制
- 使用自定义的编码器和解码器来说明 Netty 的 handler 调用机制
客户端发送 long -> 服务器
服务端发送 long -> 客户端
- 不论解码器 handler 还是 编码器 handler 即接收的消息类型必须与待处理的消息类型一致,否则该 handler 不会被执行在解码器 进行数据解码时,需要判断 缓存区(ByteBuf)的数据是否足够 ,否则接收到的结果会期望结果可能不一致
MyServer 服务器端
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38package com.xizi.inboundhandlerAndoutboundhandler; import com.xizi.neety_chat.GroupChatServerhandler; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; public class MyServer { public static void main(String[] args) { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new MyServerinittializer()); //服务器绑定端口启动 ChannelFuture channelFuture = serverBootstrap.bind(7000).sync(); //监听关闭 channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
MyServerhandler _自定义服务端处理器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24package com.xizi.inboundhandlerAndoutboundhandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class MyServerhandler extends SimpleChannelInboundHandler<Long> { @Override protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception { System.out.println("MyServerhandler 读取数据"); System.out.println("从客户端"+ctx.channel().remoteAddress()+"读取到: "+msg); //给客户端发送一个Long ctx.writeAndFlush(789456L); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
MyServerinittializer _自定义服务端初始化器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package com.xizi.inboundhandlerAndoutboundhandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; public class MyServerinittializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //接收客户端发送来的信息 入站的handler进行解码 MyByteToLongDecoder // pipeline.addLast(new MyByteToLongDecoder()); pipeline.addLast(new MyByteToLongDecoder2()); //服务器发送信息给客户端 出站得handler进行编码 MyLongToByteEncoder pipeline.addLast(new MyLongToByteEncoder()); //自定义得handler 处理业务逻辑 pipeline.addLast(new MyServerhandler()); } }
MyClient 客户端
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41package com.xizi.inboundhandlerAndoutboundhandler; import com.xizi.neety.NeetyClientHandler; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; public class MyClient { public static void main(String[] args) { //客户端创建一个事件循环组 NioEventLoopGroup group = new NioEventLoopGroup(); try { //创建客户端启动对象 //客户端使用的不是ServerBootStrap 而是bootStrop Bootstrap bootstrap = new Bootstrap(); //设置相关参数 bootstrap.group(group) //设置线程组 .channel(NioSocketChannel.class) //设置客户端通道的实现类 .handler(new MyClientInitializer()); //启动客户端去连接服务器端 // channelFuture 要分析涉及到neety的异步模型 ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 7000).sync(); //给关闭通道进行监听 channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } }
MyClientHandler 自定义客户端处理器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29package com.xizi.inboundhandlerAndoutboundhandler; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.CharsetUtil; public class MyClientHandler extends SimpleChannelInboundHandler<Long> { //客户端读取服务器发送的信息 @Override protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception { System.out.println("------------------------"); System.out.println("服务器的ip="+ctx.channel().remoteAddress()); System.out.println("收到服务器发送的消息="+msg); } //重写channelActive发送数据给服务端 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("MyClientHandler 发送数据"); ctx.writeAndFlush(123465L); //注意传入的数据类型和处理的数据类型要一致 // ctx.writeAndFlush(Unpooled.copiedBuffer("abcdabcdabcdabcd", CharsetUtil.UTF_8)); } }
MyClientInitializer 自定义客户端初始化器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25package com.xizi.inboundhandlerAndoutboundhandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; public class MyClientInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //加入一个出站的handler 对数据进行一个编码 MyLongToByteEncoder pipeline.addLast(new MyLongToByteEncoder()); //加入一个入站得handler 对数据进行一个解码 MyByteToLongDecoder // pipeline.addLast(new MyByteToLongDecoder()); pipeline.addLast(new MyByteToLongDecoder()); //加入一个自定义handler 处理业务 pipeline.addLast(new MyClientHandler()); } }
MyByteToLongDecoder 自定义解码器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28package com.xizi.inboundhandlerAndoutboundhandler; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; public class MyByteToLongDecoder extends ByteToMessageDecoder { /** * * @param ctx 上下文对象 * @param in 入站的ByteBuf * @param out list集合 将解码后的数据传给下一个handler * @throws Exception */ @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { System.out.println("MyByteToLongDecoder的decode 解码被调用"); //大于等于8个字节才能读取一个Long if (in.readableBytes()>=8){ out.add(in.readLong()); } } }
MyLongToByteEncoder 自定义编码器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package com.xizi.inboundhandlerAndoutboundhandler; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; public class MyLongToByteEncoder extends MessageToByteEncoder<Long> { //编码 客户端发送数据给服务端 进行编码 @Override protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception { System.out.println("MyLongToByteEncoder的encode编码 被调用"); System.out.println("msg="+msg); out.writeLong(msg); } }
五. 解码器-ReplayingDecoder
- ReplayingDecoder是ByteToMessageDecoder子类
复制代码
1
2class ReplayingDecoder<S> extends ByteToMessageDecoder
- ReplayingDecoder 扩展了 ByteToMessageDecoder 类,使用这个类,我们不必调用 readableBytes()方法。参数 S指定了用户状态管理的类型,其中 Void 代表不需要状态管理
- 应用实例:使用 ReplayingDecoder 编写解码器,对前面的案例进行简化
使用ReplayingDecoder解码器
其他的都是一样的 不用改
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package com.xizi.inboundhandlerAndoutboundhandler; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.ReplayingDecoder; import java.util.List; public class MyByteToLongDecoder2 extends ReplayingDecoder<Void> { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { System.out.println("MyByteToLongDecoder2的decode 解码被调用"); // ReplayingDecoder 不需要判断数据是否足够读取 内部会进行判断和处理 out.add(in.readLong()); } }
- ReplayingDecoder 使用方便,但它也有一些局限性:
- 并 不 是 所 有 的 ByteBuf 操 作 都 被 支 持 , 如 果 调 用 了 一 个 不 被 支 持 的 方 法 , 将 会 抛 出 一 个
UnsupportedOperationException。 - ReplayingDecoder 在某些情况下可能稍慢于 ByteToMessageDecoder,例如网络缓慢并且消息格式复杂时,
消息会被拆成了多个碎片,速度变慢
- 并 不 是 所 有 的 ByteBuf 操 作 都 被 支 持 , 如 果 调 用 了 一 个 不 被 支 持 的 方 法 , 将 会 抛 出 一 个
六. 其它解码器
- LineBasedFrameDecoder:这个类在 Netty 内部也有使用,它使用行尾控制字符(n 或者rn)作为分隔符来解析数据。
- DelimiterBasedFrameDecoder:使用自定义的特殊字符作为消息的分隔符。
- HttpObjectDecoder:一个 HTTP 数据的解码器
- LengthFieldBasedFrameDecoder:通过指定长度来标识整包消息,这样就可以自动的处理黏包和半包消息。
六. 其它编码器
七. Log4j 整合到 Netty
复制代码
1
2
3
4
5
6
7
8<!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
复制代码
1
2
3
4
5log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%p] %C{1} - %m%n
随便启动一个项目进程测试一下日志
最后
以上就是谦让高跟鞋最近收集整理的关于Netty学习----Netty 编解码器和 handler 的调用机制一. Netty 编解码器和 handler 的调用机制二. 编码解码器三. 解码器-ByteToMessageDecoder四. Netty 的 handler 链的调用机制五. 解码器-ReplayingDecoder六. 其它解码器六. 其它编码器七. Log4j 整合到 Netty的全部内容,更多相关Netty学习----Netty内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复