Netty學習之路(六)-分隔符和定長解碼器的應用

之前已經使用了LineBasedFrameDecoder解決TCP粘包問題,現在再學兩種解決TCP粘包的方法。

  1. DelimiterBasedFrameDecoder:可以自動完成以分隔符做結束標誌的消息的解碼,分隔符自定義。
  2. FixedLengthFrameDecoder: 固定長度解碼器,它能夠按照指定的長度對消息進行自動解碼,開發者不需要考慮TCP的粘包/拆包問題

DelimiterBasedFrameDecoder編碼實踐

與之前LineBaseFrameDecoder的使用一樣,只要將DelimiterBasedFrameDecoder和StringDecoder添加到服務端和客戶端的ChannelPipeline中。

服務端

package com.ph.Netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Create by PH on 2018/11/6
 */
public class NettyServer {

    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 NettyServer().bind(port);
    }

    public void bind(int port) throws Exception{
        //NioEventLoopGroup是一個線程組,包含了一組NIO線程,專門用於網絡事件的處理,實際上他們就是Reactor線程組
        //bossGroup僅接收客戶端連接,不做複雜的邏輯處理,爲了儘可能減少資源的佔用,取值越小越好
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //用於進行SocketChannel的網絡讀寫
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //是Netty用於啓動NIO服務端的輔助啓動類,目的是降低服務端的開發複雜度
            ServerBootstrap b = new ServerBootstrap();
            //配置NIO服務端
            b.group(bossGroup, workerGroup)
                    //指定使用NioServerSocketChannel產生一個Channel用來接收連接,他的功能對應於JDK
                    // NIO類庫中的ServerSocketChannel類。
                    .channel(NioServerSocketChannel.class)
                    //BACKLOG用於構造服務端套接字ServerSocket對象,標識當服務器請求處理線程全滿時,
                    // 用於臨時存放已完成三次握手的請求的隊列的最大長度。如果未設置或所設置的值小於1,
                    // Java將使用默認值50。
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //綁定I/O事件處理類,作用類似於Reactor模式中的Handler類,主要用於處理網絡I/O事件
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel arg0) throws Exception {
                            //定義分隔符爲"#_"
                            ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes());
                            //添加分隔符解碼器,第一個參數表示單條消息最大長度,第二個參數是分隔符緩衝對象
                            arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                            arg0.pipeline().addLast(new StringDecoder());
                            arg0.pipeline().addLast(new ServerHandler());
                        }
                    });
            //綁定端口,同步等待綁定操作完成,完成後返回一個ChannelFuture,用於異步操作的通知回調
            ChannelFuture f = b.bind(port).sync();
            //等待服務端監聽端口關閉之後才退出main函數
            f.channel().closeFuture().sync();
        } finally {
            //退出,釋放線程池資源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

/**
 * ChannelInboundHandlerAdapter實現自ChannelInboundHandler
 * ChannelInboundHandler提供了不同的事件處理方法你可以重寫
 */
class ServerHandler extends ChannelInboundHandlerAdapter {

    private int count = 0;

    /**
     * 接受客戶端發送的消息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //拿到的msg已經是解碼成字符串之後的應答消息了
        String body = (String)msg;
        ++count;
        System.out.println("Server receive: " + body + count);
        //獲得ByteBuf類型的數據
        ByteBuf resp = Unpooled.copiedBuffer(("Server message #_").getBytes());
        //向客戶端發送消息,不直接將消息寫入SocketChannel中,只是把待發送的消息放到發送緩存數組中,
        //再通過調用flush方法將緩衝區中的消息全部寫到SocketChannel中
        ctx.write(resp);
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //將消息發送隊列中的消息寫入到SocketChannel中發送給對方
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //當發生異常時釋放資源
        ctx.close();
    }
}

客戶端

package com.ph.Netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Create by PH on 2018/11/6
 */
public class NettyClient {

    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 NettyClient().connect(port, "127.0.0.1");
    }

    public void connect(int port, String host) throws  Exception{
        //配置客戶端NIO線程組
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        public void initChannel(SocketChannel ch) throws Exception{
                            //定義分隔符爲"#_"
                            ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes());
                            //添加分隔符解碼器,第一個參數表示單條消息最大長度,第二個參數是分隔符緩衝對象
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });
            //發起異步連接操作
            ChannelFuture f = b.connect(host, port).sync();
            //等待客戶端鏈路關閉
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}

class ClientHandler extends ChannelInboundHandlerAdapter {

    private  ByteBuf msg;
    private int count = 0;
    private byte[] req;

    public ClientHandler() {
        req = ("Client message " + "#_").getBytes();
    }

    /**
     * 當客戶端和服務端TCP鏈路建立成功之後,Netty的NIO線程會調用此方法
     * @param ctx
     */
    public void channelActive(ChannelHandlerContext ctx) {
        //發送消息到服務端
        for (int i=0;i<10;i++) {
            msg = Unpooled.buffer(req.length);
            msg.writeBytes(req);
            ctx.writeAndFlush(msg);
        }
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        //StringDecoder已經將ByteBuf的消息轉換成字符串,msg已經是解碼成字符串之後的應答消息了。
        String body = (String)msg;
        System.out.println("Client receive :" + body + ", the counter is:" + String.valueOf(++count));
    }

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

在DelimiterBasedFrameDecoder的使用中,要注意的是在創建其對象時的參數,第一個參數表示單條消息的最大長度,當達到該長度後仍然沒有查找到分隔符,就拋出TooLongFrameException異常,防止由於異常碼流缺失分隔符號導致的內存溢出;第二個參數就是分隔符緩衝對象。

FixedlengthFrameDecoder編碼實踐

由於與之前代碼類似,這裏就貼一部分

 protected void initChannel(SocketChannel arg0) throws Exception {
    //定義分隔符爲"#_"
    //ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes());
    //添加分隔符解碼器
    //arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
     arg0.pipeline().addLast(new FixedLengthFrameDecoder(20));
     arg0.pipeline().addLast(new StringDecoder());
     arg0.pipeline().addLast(new ServerHandler());
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章