Netty就是這麼回事(三)

由於咱們在進行服務端開發過程當中,必定會遇到TCP的粘包和分包問題,所謂粘包和分包就是由於TCP的滑動窗口以及擁塞避免等機制形成的,好比說我發一個包並非一次性發完,可能拆成多個包屢次發送,當我接收一個包時,可能會接收兩個包的組合體。那麼對於這種問題,Netty框架是如何解決的呢?這裏,我先接收一個Netty給咱們提供的能夠解決粘包和分包問題的解碼器LineBasedFrameDecoder,它的主要原理是這樣的:遍歷bytebuf中的可讀字節,將\n和\r\n斷定爲結束位置。java

接下來讓我看一下服務端的例子:bootstrap

其中LineBasedFrameDecoder已經介紹了,而StringDecoder則能夠將字節自動轉換爲子串。服務器

package com.dlb.note.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.Charset;

/**
 * 功能:支持tcp粘包/拆包的回車/換行符服務器
 * 版本:1.0
 * 日期:2016/12/9 15:21
 * 做者:馟蘇
 */
public class LineBasedFrameDecoderTimeServer {
    /**
     * main函數
     * @param args
     */
    public static void main(String []args) {
        // 構造nio線程組
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer() {
                        protected void initChannel(Channel channel) throws Exception {
                            // 遍歷bytebuf中的可讀字節,將\n和\r\n斷定爲結束位置,配置單行最大長度爲1024
                            channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            // 將字節對象轉換爲字符串
                            channel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
                            channel.pipeline().addLast(new MyHandler());
                        }
                    });
            // 綁定端口,同步等待成功
            ChannelFuture future = bootstrap.bind(8888).sync();
            System.out.println("----服務端在8888端口監聽----");

            // 等待服務端監聽端口關閉
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 優雅的退出,釋放線程池資源
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}

class MyHandler extends ChannelHandlerAdapter {
    // 客戶端連接異常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("client exception,ip=" + ctx.channel().remoteAddress());
        ctx.close();
        super.exceptionCaught(ctx, cause);
    }

    // 客戶端連接到來
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client come,ip=" + ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    // 客戶端連接關閉
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client close,ip=" + ctx.channel().remoteAddress());
        ctx.close();
        super.channelInactive(ctx);
    }

    // 可讀
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String req = (String) msg;
        System.out.println(req);

        super.channelRead(ctx, msg);
    }
}
相關文章
相關標籤/搜索