0
点赞
收藏
分享

微信扫一扫

Handler链调用机制实例

残北 2022-10-01 阅读 168
  • 使用自定义的编码器和解码器来说明Netty的handler 调用机制,客户端发送long 到服务器
  • MyServer

public class MyServer {
public static void main(String[] args) throws Exception{

EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();

try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup).channel(
NioServerSocketChannel.class).childHandler(new MyServerInitializer()); //自定义一个初始化类

ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
channelFuture.channel().closeFuture().sync();

}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}

}
}

  • MyServerInitializer

public class MyServerInitializer extends ChannelInitializer<SocketChannel> {

@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();//一会下断点

//入站的handler进行解码 MyByteToLongDecoder
pipeline.addLast(new MyByteToLongDecoder());

//自定义的handler 处理业务逻辑
pipeline.addLast(new MyServerHandler());
}
}

  • MyByteToLongDecoder

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 被调用");
//因为 long 8个字节, 需要判断有8个字节,才能读取一个long
if(in.readableBytes() >= 8) {
out.add(in.readLong());
}
}
}

  • 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);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}

  • MyClient

public class MyClient {
public static void main(String[] args) throws Exception{

EventLoopGroup 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();
}
}
}

  • MyClientInitializer

public class MyClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {

ChannelPipeline pipeline = ch.pipeline();

//加入一个出站的handler 对数据进行一个编码
pipeline.addLast(new MyLongToByteEncoder());

//加入一个自定义的handler,处理业务
pipeline.addLast(new MyClientHandler());
}
}

  • MyLongToByteEncoder

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);

}
}

  • 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);
}

//重写channelActive 发送数据
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("MyClientHandler 发送数据");
//ctx.writeAndFlush(Unpooled.copiedBuffer(""))
ctx.writeAndFlush(123456L); //发送的是一个long
}
}

  • 先启动服务端,再启动客户端

# 服务端控制台
MyByteToLongDecoder 被调用
从客户端/127.0.0.1:53008 读取到long 123456

# 客户端控制台
MyClientHandler 发送数据
MyLongToByteEncoder encode 被调用
msg=123456

  • ​服务端发送long 到客户端​
  • Handler链调用机制实例_bootstrap

  • MyServerHandler中添加如下

//给客户端发送一个long
ctx.writeAndFlush(98765L);

  • MyServerInitializer中添加如下

//出站的handler进行编码
pipeline.addLast(new MyLongToByteEncoder());

  • MyClientInitializer中添加如下

//这时一个入站的解码器(入站handler )
pipeline.addLast(new MyByteToLongDecoder());

  • 先启动服务端,再启动客户端测试

# 服务端控制台
MyByteToLongDecoder 被调用
从客户端/127.0.0.1:62913 读取到long 123456
MyLongToByteEncoder encode 被调用
msg=98765

# 客户端控制台
MyClientHandler 发送数据
MyLongToByteEncoder encode 被调用
msg=123456
MyByteToLongDecoder 被调用
服务器的ip=localhost/127.0.0.1:7000
收到服务器消息=98765

Handler链调用机制实例_ide_02

• 不论解码器handler 还是 编码器handler 即接收的消息类型必须与待处理的消息类型一致,否则该handler不会被执行
• 在解码器 进行数据解码时,需要判断 缓存区(ByteBuf)的数据是否足够 ,否则接收到的结果会期望结果可能不一致



举报

相关推荐

0 条评论