使用Netty的ReplayingDecoder解决拆包和粘包问题

概述


三篇文章中,笔者介绍了在Netty如何解决拆包和粘包问题,其中自定义解码器处理半包消息 里面介绍的方法是在线上实际用过的,经过了超级大流量的验证,挺靠谱的。下面再介绍另外一种解决半包问题的方法,虽然我没实际在线上用过,但是可以当成是一种知识补充。


直接上代码


在上面提到的三篇文章中,已经详细介绍了拆包和粘包的问题,这里不在详细说了。下面我就直接把ReplayingDecoder的代码贴一下,这些代码都是可以直接运行的。


DecoderServer

package netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class DecoderServer {
    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 DecoderServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

DecoderServerInitializer

在这里需要加入我们自定义的编码器和解码器。

package netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;


public class DecoderServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new UserDecoder());
        pipeline.addLast(new UserEncoder());

        pipeline.addLast(new DecoderServerHandler());
    }
}

UserDecoder

继承自ReplayingDecoder


package netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

public class UserDecoder extends ReplayingDecoder<Void> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int length = in.readInt();

        byte[] content = new byte[length];
        in.readBytes(content);

        UserProtocol personProtocol = new UserProtocol();
        personProtocol.setLength(length);
        personProtocol.setContent(content);

        out.add(personProtocol);
    }
}

UserEncoder

package netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class UserEncoder extends MessageToByteEncoder<UserProtocol> {

    @Override
    protected void encode(ChannelHandlerContext ctx, UserProtocol msg, ByteBuf out) throws Exception {
        out.writeInt(msg.getLength());
        out.writeBytes(msg.getContent());
    }
}

UserProtocol

自定义协议。

package netty;

public class UserProtocol {

    private int length;

    private byte[] content;

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public byte[] getContent() {
        return content;
    }

    public void setContent(byte[] content) {
        this.content = content;
    }
}

DecoderServerHandler

package netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

public class DecoderServerHandler extends SimpleChannelInboundHandler<UserProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, UserProtocol msg) throws Exception {
        int length = msg.getLength();
        byte[] content = msg.getContent();

        System.out.println("服务端接收到的消息:" + new String(content, Charset.forName("utf-8")));

        System.out.println("服务端接收到的消息数量:" + (++this.count));

        String responseMessage = UUID.randomUUID().toString();
        int responseLength = responseMessage.getBytes("utf-8").length;
        byte[] responseContent = responseMessage.getBytes("utf-8");

        UserProtocol userProtocol = new UserProtocol();
        userProtocol.setLength(responseLength);
        userProtocol.setContent(responseContent);

        ctx.writeAndFlush(userProtocol);
    }

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


下面贴一下Netty客户端的代码。

DecoderClient

package netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class DecoderClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).
                    handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new UserDecoder());
                            pipeline.addLast(new UserEncoder());

                            pipeline.addLast(new DecoderClientHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}

DecoderClientHandler

package netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

public class DecoderClientHandler extends SimpleChannelInboundHandler<UserProtocol> {

    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 3; ++i) {
            String messageToBeSent = "sent from client ";
            byte[] content = messageToBeSent.getBytes(Charset.forName("utf-8"));
            int length = messageToBeSent.getBytes(Charset.forName("utf-8")).length;

            UserProtocol userProtocol = new UserProtocol();
            userProtocol.setLength(length);
            userProtocol.setContent(content);

            ctx.writeAndFlush(userProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, UserProtocol msg) throws Exception {
        int length = msg.getLength();
        byte[] content = msg.getContent();

        System.out.println("客户端接收到的内容:" + new String(content, Charset.forName("utf-8")));

        System.out.println("客户端接受到的消息数量:" + (++this.count));
    }

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

运行结果


服务端

服务端接收到的消息:sent from client 
服务端接收到的消息数量:1
服务端接收到的消息:sent from client 
服务端接收到的消息数量:2
服务端接收到的消息:sent from client 
服务端接收到的消息数量:3

客户端

客户端接收到的内容:3879cc39-2bfd-4ca4-826a-91658bfcd97d
客户端接受到的消息数量:1
客户端接收到的内容:a63108e6-4e45-41e2-b78b-31228461e3ce
客户端接受到的消息数量:2
客户端接收到的内容:f760b6c1-5c42-4fa7-8fa2-32b1941c7f9d
客户端接受到的消息数量:3

可见用ReplayingDecoder 可以解决拆包和粘包的问题。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值