netty对应的TCP粘包和拆包和解决方案

1、TCP是面向连接的,面向流的,提供高可靠性服务。收发两端(客户端和服务器端)都要有一一成对的socket,因此,发送端为了将多个发给接收端的包,更有效的发给对方,使用了优化方法(Nagle算法),将多次间隔较小且数据量小的数据,合并成一个大的数据块,然后进行封包。这样做虽然提高了效率,但是接收端就难于分辨出完整的数据包了,因为面向流的通信是无消息保护边界的
2、由于TCP无消息保护边界, 需要在接收端处理消息边界问题,也就是我们所说的粘包、拆包问题, 看一张图

netty对应的TCP粘包和拆包和解决方案_第1张图片

2.1、假设客户端分别发送了两个数据包D1和D2给服务端,由于服务端一次读取到字节数是不确定的,故可能存在以下四种情况:
2.2、服务端分两次读取到了两个独立的数据包,分别是D1和D2,没有粘包和拆包
2.3、服务端一次接受到了两个数据包,D1和D2粘合在一起,称之为TCP粘包
2.4、服务端分两次读取到了数据包,第一次读取到了完整的D1包和D2包的部分内容,第二次读取到了D2包的剩余内容,这称之为TCP拆包
2.5、服务端分两次读取到了数据包,第一次读取到了D1包的部分内容D1_1,第二次读取到了D1包的剩余部分内容D1_2和完整的D2包。

3、解决方案:

3.1、使用自定义协议 + 编解码器 来解决
3.2、关键就是要解决 服务器端每次读取数据长度的问题, 这个问题解决,就不会出现服务器多读或少读数据的问题,从而避免的TCP 粘包、拆包 。

4、代码

协议包:
public class MessageProtocol {

    private int len;
    private byte[] content;

    public int getLen() {
        return len;
    }

    public void setLen(int len) {
        this.len = len;
    }

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

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

解码器:

public class MyMessageDecoder extends ReplayingDecoder {
    /**
     * 解码器
     * @param ctx
     * @param byteBuf
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List list) throws Exception {
        System.out.println("MyMessageDecoder解码器被调用...");
        //将得到的二进制转换为字节码  MessageProtocol数据包对象
        int len = byteBuf.readInt();
        byte[] content = new byte[len];
        byteBuf.readBytes(content);
        //封装成MessageProtocol对象信息
        MessageProtocol protocol = new MessageProtocol();
        protocol.setLen(len);
        protocol.setContent(content);
        list.add(protocol);
    }
}
 

编码器:

public class MyMessageEncoder extends MessageToByteEncoder {

    /**
     * 编码器的方法
     * @param ctx
     * @param messageProtocol
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, MessageProtocol messageProtocol, ByteBuf byteBuf) throws Exception {
        System.out.println("MyMessageEncoder 编码器被运行...");
        byteBuf.writeInt(messageProtocol.getLen());
        byteBuf.writeBytes(messageProtocol.getContent());
    }
}

服务端

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 ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //添加编码器
                            pipeline.addLast(new MyMessageEncoder());
                            //添加解码器
                            pipeline.addLast(new MyMessageDecoder());
                            //添加自定义处理器
                            pipeline.addLast(new MyServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8088).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

服务端对于的handler:

public class MyServerHandler extends SimpleChannelInboundHandler {
    private int count;

    /**
     * 处理客户端的数据并且给客户端发送信息
     * @param ctx
     * @param messageProtocol
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol messageProtocol) throws Exception {
        int len = messageProtocol.getLen();
        byte[] content = messageProtocol.getContent();
        System.out.println();
        System.out.println("服务器接收的信息如下:");
        System.out.println("信息的长度:" + len);
        System.out.println("信息的内容:" + new String(content,Charset.forName("utf-8")));
        System.out.println("服务器接收消息的数量:" + (++count));
        System.out.println();
        //给客户端回复信息
        String uuidContent = UUID.randomUUID().toString();
        int responseLen = uuidContent.getBytes("utf-8").length;
        byte[] responseContent = uuidContent.getBytes("utf-8");
        //增加一个协议包
        MessageProtocol responseProtocol = new MessageProtocol();
        responseProtocol.setLen(responseLen);
        responseProtocol.setContent(responseContent);
        ctx.writeAndFlush(responseProtocol);
    }

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

客户端:

public class MyClient {

    public static void main(String[] args) throws Exception{
        NioEventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //添加编解码器
                            //添加编码器
                            pipeline.addLast(new MyMessageEncoder());
                            //添加解码器
                            pipeline.addLast(new MyMessageDecoder());
                            //添加自定义处理器
                            pipeline.addLast(new MyClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8088).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }

    }
}

客户端对于的handler:

public class MyClientHandler extends SimpleChannelInboundHandler {

    private int count;
    /**
     * 发送数据到客户端
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 5; i++) {
            String msg = "你好啊,服务端大哥" + i;
            int len = msg.getBytes("utf-8").length;
            byte[] content = msg.getBytes("UTF-8");
            MessageProtocol protocol = new MessageProtocol();
            protocol.setLen(len);
            protocol.setContent(content);
            ctx.writeAndFlush(protocol);
        }
    }

    /**
     * 读取服务端的数据信息
     * @param ctx
     * @param messageProtocol
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol messageProtocol) throws Exception {
        int len = messageProtocol.getLen();
        byte[] content = messageProtocol.getContent();
        //转换为字符串
        String contentStr = new String(content,Charset.forName("UTF-8"));
        System.out.println("客户端发送数据的长度为:" + len);
        System.out.println("客户端发送的数据内容为:" + contentStr);
        System.out.println("客户端接收消息的数量:" + (++count));


    }

    /**
     * 处理异常信息
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}


 

 

你可能感兴趣的:(netty,java,netty)