Netty 样例代码如下
客户端
// Configure the client. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline( new EchoClientHandler(firstMessageSize)); } }); // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection is closed or the connection attempt fails. future.getChannel().getCloseFuture().awaitUninterruptibly(); // Shut down thread pools to exit. bootstrap.releaseExternalResources();
服务器端
// Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(port)); }
处理流程
NioClientSocketPipelinesink由NioClientSocketChannelFactory创建,责任是分发事件处理
AbstractNioSelector是netty心脏,下面是客户端的AbstractNioSelector实现,包括NioClientBoss,NioWorker,没有画出的部分是服务器端的NioServerBoss,他们的职责及其区别如下流程
NioClientBoss,NioServerBoss,NioWorker联系与区别如下。
如上所述NioClientSocketPipelinesink和NioServerSocketPipelinesink分别处理客户端服务器端的由Boostrap触发的事件,有本事身为AbstractNioSelector的Boss线程NioClientBoss,NioServerBoss处理,NioClientBoss处理OP_CONNECT,NioServer处理OP_ACCEPT。
NioClientBoss完成连接后,交由NioWorker线程处理;NioWorker在连接之前已经创建
NioServerBoss接受到多个连接后,交由NioWorker线程处理;NioWorker在接受到连接后创建。递交给NioWorker的方式通过注册到NioWorker任务队列中,当有后续的交互操作时NioWorker会处理任务队列