Netty解决分包的几种解码器介绍

一:LineBaseFrameDecoder 换行符解码器
改解码器的原理是,以此遍历缓存数组里的字节,判断字节是否为“\n”或者“\r\n”,如果读到了,就任务是数据包的结束位置,这样从遍历的start position到end position 这个闭区间就可以截取出一个完整的业务数据包。这种方式的缺点可以在数据的其他位置中包含这两个字符,导致截取数据错误,那么为了保障数据的正确性,一般多加一个固定的长度,如果寻找字符的区间长度大于这个固定的长度,认为数据有问题,那么就把这个数据扔掉,接着读下面的数据。

二:DelimiterBaseFrameDecoder 定界符解码器
该解码器可以自动完成以定界符为码流结束标志,然后截取数据包。下面通过一个案例来演示一下这个解码器的使用。
客户端代码:
public class DelimiterClientTime {
private static final int PORT = 8080;
private static final String IP = “127.0.0.1”;
public static void main(String[] args) throws InterruptedException {
new DelimiterClientTime().connect(PORT, IP);
}
public void connect(int port, String host) throws InterruptedException {
//创建时间顺循环线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//socket通道管道加入行解码器
ByteBuf delimiter = Unpooled.copiedBuffer(“#_”.getBytes());
//传输遍历的数据长度和界定符“#_”
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
//socket通道管道加入字符串解码器
socketChannel.pipeline().addLast(new StringDecoder());
//socket通道管道加入客户端发送数据的适配器
socketChannel.pipeline().addLast(new DelimiterClientHandler());
}
});
//发起异步连接,连接指定的主机,指定主机ip和port
ChannelFuture f = bootstrap.connect(host, port).sync();
//等待客户端链路关闭
f.channel().closeFuture().sync();
} finally {
//释放线程组
group.shutdownGracefully();
}
}
}
public class DelimiterClientHandler extends ChannelHandlerAdapter {
private int counter;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
for (int i = 0; i < 100; i++) {
ctx.writeAndFlush(Unpooled.copiedBuffer((“HI Netty” + “#_”).getBytes()).toString());
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(“this is ” + (++counter) + ” receive server message” + msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println(“读取完成”);
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
System.out.println(“客户端异常退出”);
}
}

服务器代码:
public class DelimiterDecoderServer {
public static void main(String[] args) throws InterruptedException {
DelimiterDecoderServer delimiterDecoderServer = new DelimiterDecoderServer();
delimiterDecoderServer.bind(8080);
}
public void bind(int port) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ByteBuf delimiter = Unpooled.copiedBuffer(“#_”.getBytes());
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new DelimiterDecoderServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class DelimiterDecoderServerHandler extends ChannelHandlerAdapter {
private int counter;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println(“This is ” + (++counter) + ” receive client msg ” + body);
String sendContent = “receive message is ok:” + “#_”;
ByteBuf byteBuf = Unpooled.copiedBuffer(sendContent.getBytes());
ctx.writeAndFlush(byteBuf);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值