Netty学习之---TCP粘包和拆包

来源:互联网 发布:淘宝网红模特虎牙 编辑:程序博客网 时间:2024/06/08 14:43
TCP粘包/拆包问题:
1.TCP是个“流协议”,所谓流,就是没有界限的一串数据。
2.它会根据TCP缓冲区的实际情况进行包的划分,所以在业务上认为,一个完整的包可能会被
    TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是TCP粘包
            和拆包问题。
3.TCP粘包/拆包发生的原因:
①应用程序write写入的字节大小大于套接口发送缓冲区大小;
②进行MSS大小的TCP分段;
③以太网帧的payload大于MTU进行IP分片。
4.粘包问题的解决策略:
(1).消息定长:例如每个报文的大小问固定长度200字节,如果不够,空格补位;
(2).在包尾增加回车换行符进行分割,例如FTP协议;
(3).将消息分为消息头和消息体,消息头中包含表示消息总长度的字段

(4).更复杂的应用层协议。

下面是Netty以解决的粘包和拆包的案例:

服务端代码:

public class TcpServer {    public static void main(String[] args) {        new TcpServer().blind(6789);    }    public void blind(int port){        NioEventLoopGroup bossGroup = new NioEventLoopGroup();        NioEventLoopGroup workGroup = new NioEventLoopGroup();        try{            ServerBootstrap b = new ServerBootstrap();            b.group(bossGroup,workGroup)                    .channel(NioServerSocketChannel.class)                    .option(ChannelOption.SO_BACKLOG,1024)                    .childHandler(new ChannelInitializer<SocketChannel>() {                        @Override                        protected void initChannel(SocketChannel socketChannel) throws Exception {                            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));                             socketChannel.pipeline().addLast(new StringDecoder());                            socketChannel.pipeline().addLast(new TcpServerHandler());                        }                    });            ChannelFuture f = b.bind(port).sync();            f.channel().closeFuture().sync();        } catch (InterruptedException e) {            e.printStackTrace();        }finally {            bossGroup.shutdownGracefully();            workGroup.shutdownGracefully();        }    }}
服务端处理类:

public class TcpServerHandler extends ChannelHandlerAdapter{    private int counter;    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        /*ByteBuf buf = (ByteBuf) msg;        byte[] req = new byte[buf.readableBytes()];        buf.readBytes(req);        String body = new String(req,"utf-8");*/    //加LineBasedFrameDecoder和StringDecoder之前        String body = (String) msg;  //加LineBasedFrameDecoder和StringDecoder之后        System.out.println("The server receive order :" +body                        +"; the serverCounter is :"+ ++counter);        String currentTime = "QUERY TIME ORDER".equals(body)?                new Date(System.currentTimeMillis()).toString():"BAD ORDER";        currentTime = currentTime+System.getProperty("line.separator");        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());        ctx.writeAndFlush(resp);    }    /*@Override    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {        ctx.flush();    }*/    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {        ctx.close();    }}
客户端代码:

public class TcpClient {    public static void main(String[] args) {        new TcpClient().connect(6789,"127.0.0.1");    }    public void connect(int port,String host){        NioEventLoopGroup group = new NioEventLoopGroup();        try {            Bootstrap b = new Bootstrap();            b.group(group).channel(NioSocketChannel.class)                    .option(ChannelOption.TCP_NODELAY,true)                    .handler(new ChannelInitializer<SocketChannel>() {                        @Override                        protected void initChannel(SocketChannel socketChannel) throws Exception {                            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));                            socketChannel.pipeline().addLast(new StringDecoder());                            socketChannel.pipeline().addLast(new TcpClientHandler());                        }                    });            ChannelFuture f = b.connect(host,port).sync();            f.channel().closeFuture().sync();        } catch (InterruptedException e) {            e.printStackTrace();        }finally {            group.shutdownGracefully();        }    }}
客户端消息处理类:

public class TcpClientHandler extends ChannelHandlerAdapter{    private static final Logger logger = Logger            .getLogger(TcpClientHandler.class.getName());    private int counter;    private byte[] req;    public TcpClientHandler() {        req = ("QUERY TIME ORDER"+System.getProperty("line.separator")).getBytes();    }    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        ByteBuf message = null;        for (int i = 0;i<100;i++){            message = Unpooled.buffer(req.length);            message.writeBytes(req);            ctx.writeAndFlush(message);        }    }    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        /*ByteBuf buf = (ByteBuf) msg;        byte[] req = new byte[buf.readableBytes()];        buf.readBytes(req);        String body = new String(req,"UTF-8");*/        String body = (String) msg; //加LineBasedFrameDecoder和StringDecoder之后        System.out.println("Now is : "+body+"; the clientCounter is :"+ ++counter);    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {        logger.warning("Unexpected exception from downStream:"                        +cause.getMessage());        ctx.close();    }}
5.LineBasedFrameDecoder和StringDecoder的原理分析:
  LineBasedFrameDecoder的工作原理是它依次遍历ByteBuf中的可读字节,判断看是否有
“\n”或者“\r\n”,如果有就以此位置结束,从可读索引到结束位置区间的字节就组成了一行。
它是以换行符为结束标志的解码器,支持携带结束符或者不携带结束符两种解码方式。

StringDecoder的功能非常简单,就是将接受到的对象转换成字符串,然后继续调用后面的handler。
LineBasedFrameDecoder和StringDecoder组合就是按行切换的文本解码器,它被设计用来支持
TCP的粘包和拆包。