Netty 自定义编码解码器,处理TCP粘包拆包问题

自定义编码解码器,处理TCP粘包拆包问题

具体代码实现
自定义编码解码器
PersonProtocol
public class PersonProtocol {

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


MyPersonDecoder
//  编写解码器
public class MyPersonDecoder extends ReplayingDecoder<Void> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
         System.out.println("MyPersonDecoder decode invoked!");

         int length = in.readInt();

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

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

         out.add(personProtocol);
    }
}



MyPersonEncoder
//  编码器
public class MyPersonEncoder extends MessageToByteEncoder<PersonProtocol> {

    @Override
    protected void encode(ChannelHandlerContext ctx, PersonProtocol msg, ByteBuf out) throws Exception {
        System.out.println("MyPersonEncoder encode invoked!");

        out.writeInt(msg.getLength());
        out.writeBytes(msg.getContent());
    }
}


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

        //  事件线程组   eventLoopGroup
        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 MyPersonEncoder());
                            pipeline.addLast(new MyPersonDecoder());

                            pipeline.addLast(new MyClientHandler());
                        }
                    }); //  通道初始化

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


MyClientHandler
public class MyClientHandler extends SimpleChannelInboundHandler<PersonProtocol> {

    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersonProtocol msg) throws Exception {

        int length=msg.getLength();
        byte[] content = msg.getContent();

        System.out.println("客户端接收到消息");

        System.out.println("长度:"+length);
        System.out.println("内容:"+new String(content, Charset.forName("utf-8")));

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

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for(int i=0;i<10;i++){
            String messageToBeSent = "发送自客户端";
            byte[] content = messageToBeSent.getBytes(Charset.forName("utf-8"));
            int length = messageToBeSent.getBytes(Charset.forName("utf-8")).length;

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

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



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

        //两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();//启动服务器
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
                    handler(new LoggingHandler(LogLevel.INFO)). //  指定日志处理器 日志级别  针对bossGroup
                    childHandler(new MyServerInitialzer());//  指定日志级别  针对workerGroup

            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();//绑定端口
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();// 关闭线程组
            workerGroup.shutdownGracefully();
        }
    }
}



MyServerInitialzer

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

        pipeline.addLast(new MyPersonDecoder());
        pipeline.addLast(new MyPersonEncoder());

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


MyServerHandler
public class MyServerHandler extends SimpleChannelInboundHandler<PersonProtocol> {
    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersonProtocol msg) throws Exception {

        int length = msg.getLength();
        byte[] content = msg.getContent();

        System.out.println("服务端接受到数据:");
        System.out.println("长度:"+length);
        System.out.println("内容:"+new String (content, Charset.forName("utf-8")));

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

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

        PersonProtocol personProtocol = new PersonProtocol();
        personProtocol.setContent(responseContent);
        personProtocol.setLength(responseLength);

        ctx.writeAndFlush(personProtocol);
    }

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

猜你喜欢

转载自blog.csdn.net/weixin_45623983/article/details/128700101