文章目录
第6章 Netty编解码器和Handler调用机制
1 基本说明


2 编解码器

3 解码器-ByteToMessageDecoder



4 Netty的Handler链调用机制
-
实例要求:
使用自定义的编码器和解码器来说明Netty的Handler调用机制
客户端发送long -> 服务器
服务端发送long -> 客户端

-
案例演示

public class MyServer { public static void main(String[] args) throws InterruptedException { NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup,workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new MyServerInitializer()); ChannelFuture channelFuture = serverBootstrap.bind(7000).sync(); System.out.println("服务器就绪"); channelFuture.channel().closeFuture().sync(); }finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }public class MyServerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //入站的handler进行解码 MyByteToLongDecoder pipeline.addLast(new MyByteToLongDecoder()); pipeline.addLast(new MyLongToByteEncoder()); pipeline.addLast(new MyServerHandler()); } }public class MyServerHandler extends SimpleChannelInboundHandler<Long> { @Override protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception { System.out.println("从客户端" + ctx.channel().remoteAddress() + "读取到long:" + msg); ctx.writeAndFlush(987654L); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }public class MyClient { public static void main(String[] args) throws InterruptedException { NioEventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new MyClientInitializer()); ChannelFuture channelFuture = bootstrap.connect("localhost", 7000).sync(); channelFuture.channel().closeFuture().sync(); }finally { group.shutdownGracefully(); } } }public class MyClientInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //加入一个出站的handler,对数据进行编码 pipeline.addLast(new MyLongToByteEncoder()); pipeline.addLast(new MyByteToLongDecoder()); //加入一个自定义的handler,处理业务 pipeline.addLast(new MyClientHandler()); } }public class MyClientHandler extends SimpleChannelInboundHandler<Long> { @Override protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception { System.out.println("服务器ip="+ctx.channel().remoteAddress()); System.out.println("收到服务器数据:"+msg); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("MyClientHandler 发送数据"); ctx.writeAndFlush(123456L); //1."abcdabcdabcdabcd" 16个字节 //ctx.writeAndFlush(Unpooled.copiedBuffer("abcdabcdabcdabcd", CharsetUtil.UTF_8)); } }public class MyByteToLongDecoder extends ByteToMessageDecoder { /*** * decode会根据接收到的数据被调用多次,直到确定没有新的元素被添加到List * 或者是ByteBuf没有更多的可读字节为止 * 如果List out不为空,就会将List的内容传递给下一个ChannelInboundhandler处理,该处理器的方法也会被调用多次 * @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 被调用"); //需要判断至少有8个字节,才能读取一个Long if (in.readableBytes() >= 8){ out.add(in.readLong()); } } }public class MyLongToByteEncoder extends MessageToByteEncoder<Long> { /** * 编码方法 * * @param ctx * @param msg * @param out * @throws Exception */ @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); } } -
结论
不论解码器handler还是编码器handler,接收的消息类型必须和待处理的的消息类型一致,否则该handler不会执行。
在解码器进行数据解码时,需要判断缓存区(ByteBuf)的数据是否足够,否则接收到的结果与期望结果可能不一致。
5 解码器-ReplayingDecoder


public class MyByteToLongDecoder2 extends ReplayingDecoder<Void> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
System.out.println("MyByteToLongDecoder2 被调用");
//在ReplayingDecoder 不需要判断数据是否足够读取,内部进行处理判断
out.add(in.readLong());
}
}
6 其他解码器

7 其他编码器

8 Log4j整合Netty
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
log4j.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

479




被折叠的 条评论
为什么被折叠?



