Netty使用DelimiterBasedFrameDecoder解决TCP粘包拆包问题

通过对DelimiterBasedFrameDecoder的使用,我们可以自动完成分隔符为结束标识的消息的解码。

下面的例子中,将$_作为分隔符。

服务端代码:

/**
 * 使用DelimiterBasedFrameDecoder解码器解决TCP粘包/拆包问题。
 *
 * @author j.tommy
 * @version 1.0
 * @date 2017/11/17
 */
public class EchoServer {
    protected final static String DELIMITER = "$_";
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ByteBuf delimiter = Unpooled.copiedBuffer(DELIMITER.getBytes());
                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter)); // 这里的1024标识单条消息的最大长度,如果达到长度后仍然没有读取到分隔符,就抛出TooLongFrameException,防止由于异常码流缺失导致的内存溢出,这是Netty解码器的可靠性保护;第二个参数是分隔符
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new EchoServerHandler());
                    }
                });
        try {
            ChannelFuture f = b.bind(8899).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
class EchoServerHandler extends ChannelHandlerAdapter {
    private int counter;
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        System.out.println("接收到客户端请求:" + body + ",counter=" + ++counter);
        // 响应客户端
        body += EchoServer.DELIMITER;
        ByteBuf resp = Unpooled.copiedBuffer(body.getBytes());
        ctx.write(resp);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}

客户端代码:

/**
 * @author j.tommy
 * @version 1.0
 * @date 2017/11/17
 */
public class EchoClient {
    protected final static String DELIMITER = "$_";
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true).handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ByteBuf delimiter = Unpooled.copiedBuffer(DELIMITER.getBytes());
                socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
                socketChannel.pipeline().addLast(new StringDecoder());
                socketChannel.pipeline().addLast(new EchoClientHandler());
            }
        });
        try {
            ChannelFuture f = b.connect("127.0.0.1",8899).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            group.shutdownGracefully();
        }
    }
}

class EchoClientHandler extends ChannelHandlerAdapter {
    private int counter = 0;
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String req = "hello,this message is from client."+EchoClient.DELIMITER;
        ByteBuf sendBuf = null;
        for (int i=0;i<100;i++) {
            sendBuf = Unpooled.copiedBuffer(req.getBytes());
            ctx.writeAndFlush(sendBuf);
        }
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String resp = (String) msg;
        System.out.println("接收到服务端响应:"  + resp + ",counter=" + ++counter);
    }
}

参考《Netty权威指南》

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值