Netty(三)

熟悉TCP編程的讀者可能都會知道,不管是服務端仍是客戶端,當咱們讀取或者發送消息的時候,都須要考慮TCP底層的粘包/拆包機制。這裏,首先講述下基本知識,而後模擬一個沒有考慮TCP粘包/拆包致使功能異常的案例,幫助你們進行分析。java

1、基礎知識編程

問題說明ide

一般,會發生上圖中的4種狀況:oop

1  正常  2  粘包  三、4  拆包測試

緣由:線程

1  應用程序寫入的字節大小大於套接口發送緩衝區大小;設計

2  進行MSS大小的TCP分段;code

3  以太網幀的payload大於MTU進行IP分片。orm

解決方案:server

因爲底層是沒法保證數據包不被拆分和重組的,這個問題只能經過上層的應用協議棧設計來解決概括以下:

1  消息定長

2  在包尾增長回車換行符進行分割,例如FTP協議

3  message分爲消息頭和消息體

4  更復雜的應用層協議

2、沒有考慮TCP粘包/拆包致使功能異常的案例

在功能測試時每每沒有問題,可是壓力測試過程當中,問題就會暴露出來。若是代碼沒有考慮,每每就會出現解碼錯位或者錯誤,致使程序不能工做。

public class TimeServerHandler 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").substring(0, req.length 
            - System.getProperty("line.separator").length());
        System.out.println("The time server receive order : " + body
            + " ; the counter is : " + ++counter);
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
        System.currentTimeMillis()).toString() : "BAD ORDER";
        currentTime = currentTime + System.getProperty("line.separator");
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.writeAndFlush(resp);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
public class TimeClientHandler extends ChannelHandlerAdapter {

    private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());

    private int counter;

    private byte[] req;

    public TimeClientHandler() {
        req = ("QUERY TIME ORDER" + System.getProperty("line.separator").getBytes();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        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()];
        byte.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println("Now is : " + body + " ; the counter is : " + ++counter);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        
        logger.warning("Unexpected exception from downstream : " + cause.getMessage());
        ctx.close();
    }
}

服務端運行結果顯示只發送了兩條請求消息,於是客戶端理應也返回了兩條「BAD ORDER」應答消息,可是

事實是客戶端只返回了一條包含兩個「BAD ORDER」指令的消息,說明服務端和客戶端都發生了粘包。

3、Netty是如何解決TCP粘包問題的

Netty默認提供了多種編解碼器用於處理半包。

支持TCP粘包的TimeServer

public class TimeServer {

    public void bind(int port) throws Exception {
        //配置服務端的NIO線程組
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChildChannelHandler());
            //綁定端口,同步等待成功
            ChannelFuture f = b.bind(port).sync();

            //等待服務端監聽端口關閉
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel arg0) throws Exception {
            arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
            arg0.pipeline().addLast(new StringDecoder());
            arg0.pipeline().addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if(args!=null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch(NumberFormatException e) {
            }
        }
        new TimeServer().bind(port);
    }
}

public class TimeServerHandler extends ChannelHandlerAdapter {
    private int counter;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        System.out.println("The time server receive order : " + body + " ; the counter is : " + ++ counter);
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
            System.currentTimeMillis()).toString() : "BAD ORDER";
        currentTime = currentTime + System.getProperty("line.separator");
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.writeAndFlush(resp);
    }

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

運行結果徹底符合預期,說明經過使用LineBasedFrameDecoder和StringDecoder成功解決了TCP粘包致使的讀半包問題。

只要將支持半包解碼的Handler添加到ChannelPipeline中便可,不須要寫額外的代碼,用起來很方便。

4、LineBasedFrameDecoder和StringDecoder的原理分析

簡單地來講,LineBasedFrameDecoder是以換行符爲結束標誌的解碼器,同事支持配置當行的最大長度。若是連續讀取到最大長度house仍然沒有發現換行符,就會拋出異常,同時忽略以前讀到的異常碼流。

而StringDecoder是將接收到的對象轉換成字符串,而後繼續調用後面的Handler。

相關文章
相關標籤/搜索