Netty源碼分析(一):Netty總覽

作為當(dāng)前最流行的網(wǎng)絡(luò)通信框架,Netty在互聯(lián)網(wǎng)領(lǐng)域大放異彩,本系列將詳細(xì)介紹Netty(4.1.22.Final)。

代碼事例

服務(wù)端

public final class EchoServer {
    // 從啟動參數(shù)判斷是否使用ssl
    static final boolean SSL = System.getProperty("ssl") != null;
    // 獲取端口(默認(rèn)8007)
    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));

    public static void main(String[] args) throws Exception {
        // 配置SSL
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }
        // 配置服務(wù)器
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc()));
                            }
                            // 添加一個自定義的handler
                            p.addLast(new EchoServerHandler());
                        }
                    });
            // 啟動服務(wù)器
            ChannelFuture f = b.bind(PORT).sync();
            // 等待至連接斷開
            f.channel().closeFuture().sync();
        } finally {
            // 關(guān)閉服務(wù)器資源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

客戶端

public final class EchoClient {
    // 獲取是否使用ssl
    static final boolean SSL = System.getProperty("ssl") != null;
    // 獲取服配置的服務(wù)器地址(默認(rèn)本地)
    static final String HOST = System.getProperty("host", "127.0.0.1");
    // 獲取端口(默認(rèn)8007)
    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
    // 首次發(fā)送消息的大小
    static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));

    public static void main(String[] args) throws Exception {
        // 配置SSL
        final SslContext sslCtx;
        if (SSL) {
            sslCtx = SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            sslCtx = null;
        }
        // 配置客戶端
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    // 禁用Nagle算法
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                            }
                            //p.addLast(new LoggingHandler(LogLevel.INFO));
                            p.addLast(new EchoClientHandler());
                        }
                    });
            // 啟動客戶端
            ChannelFuture f = b.connect(HOST, PORT).sync();
            //等待至連接斷開
            f.channel().closeFuture().sync();
        } finally {
            // 關(guān)閉客戶端資源
            group.shutdownGracefully();
        }
    }
}

運行流程

服務(wù)器

image

客戶端

image

總結(jié)

本篇篇幅較短,只是簡單貼了一段netty-example下面的代碼,并梳理了一下netty的流程。接下來的幾篇會詳細(xì)介紹netty服務(wù)端和客戶端啟動時做了哪些事情。
我目前正在嘗試在給netty添加注釋:https://github.com/KAMIJYOUDOUMA/nettyForAnalysis.git ,有興趣的童鞋可以關(guān)注一下。


本篇到此結(jié)束,如果讀完覺得有收獲的話,歡迎點贊、關(guān)注、加公眾號【貳級天災(zāi)】,查閱更多精彩歷史!?。?/p>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。