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

做爲當前最流行的網絡通訊框架,Netty在互聯網領域大放異彩,本系列將詳細介紹Netty(4.1.22.Final)。java

代碼事例

服務端

public final class EchoServer {
    // 從啓動參數判斷是否使用ssl
    static final boolean SSL = System.getProperty("ssl") != null;
    // 獲取端口(默認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;
        }
        // 配置服務器
        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());
                        }
                    });
            // 啓動服務器
            ChannelFuture f = b.bind(PORT).sync();
            // 等待至鏈接斷開
            f.channel().closeFuture().sync();
        } finally {
            // 關閉服務器資源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
複製代碼

客戶端

public final class EchoClient {
    // 獲取是否使用ssl
    static final boolean SSL = System.getProperty("ssl") != null;
    // 獲取服配置的服務器地址(默認本地)
    static final String HOST = System.getProperty("host", "127.0.0.1");
    // 獲取端口(默認8007)
    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
    // 首次發送消息的大小
    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 {
            // 關閉客戶端資源
            group.shutdownGracefully();
        }
    }
}
複製代碼

運行流程

服務器

客戶端

總結

本篇篇幅較短,只是簡單貼了一段netty-example下面的代碼,並梳理了一下netty的流程。接下來的幾篇會詳細介紹netty服務端和客戶端啓動時作了哪些事情。 我目前正在嘗試在給netty添加註釋:github.com/KAMIJYOUDOU… ,有興趣的童鞋能夠關注一下。git


本篇到此結束,若是讀完以爲有收穫的話,歡迎點贊、關注、加公衆號【貳級天災】,查閱更多精彩歷史!!! github

相關文章
相關標籤/搜索