31.Netty源码之客户端启动流程
客户端启动主要流程
如果看了服务器端的启动流程,这里简单看下就可以了。
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