31.Netty源码之客户端启动流程

2023年 8月 18日 51.5k 0

客户端启动主要流程

如果看了服务器端的启动流程,这里简单看下就可以了。

package io.netty.server;
​
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
​
​
public final class EchoClient {
​
    public static void main(String[] args) throws Exception {
        // Configure the client.
        EventLoopGroup group = new NioEventLoopGroup();
        ChannelInitializer channelInitializer = new ChannelInitializer() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                //  p.addLast(new LoggingHandler(LogLevel.INFO));
                p.addLast(new EchoClientHandler());
            }
        };
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .option(ChannelOption.TCP_NODELAY, true)
             .handler(channelInitializer);
​
            // Start the client.
            ChannelFuture f = b.connect("127.0.0.1", 8090).sync();
​
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down the event loop to terminate all threads.
            group.shutdownGracefully();
        }
    }
}
​
​

创建客户端NioSocketChannel

1.创建NioSocketChannel

首先看下创建 Channel 的过程,直接跟进 channelFactory.newChannel() 的源码。

public class ReflectiveChannelFactory implements ChannelFactory {
   private final Constructor

相关文章

服务器端口转发,带你了解服务器端口转发
服务器开放端口,服务器开放端口的步骤
产品推荐:7月受欢迎AI容器镜像来了,有Qwen系列大模型镜像
如何使用 WinGet 下载 Microsoft Store 应用
百度搜索:蓝易云 – 熟悉ubuntu apt-get命令详解
百度搜索:蓝易云 – 域名解析成功但ping不通解决方案

发布评论