从netty-example分析Netty组件

分析netty从源码开始
准备工作:
1.下载源代码:https://github.com/netty/netty.git
我下载的版本为4.1
2. eclipse导入maven工程 。
netty提供了一个netty-example工程,

从netty-example分析Netty组件

文章插图
 
分类如下:
Fundamental
  • Echo ‐ the very basic client and server
  • Discard ‐ see how to send an infinite data stream asynchronously without flooding the write buffer
  • Uptime ‐ implement automatic reconnection mechanism
Text protocols
  • Telnet ‐ a classic line-based network Application
  • Quote of the Moment ‐ broadcast a UDP/IP packet
  • SecureChat ‐ an TLS-based chat server, derived from the Telnet example
Binary protocols
  • ObjectEcho ‐ exchange serializable JAVA objects
  • Factorial ‐ write a stateful client and server with a custom binary protocol
  • WorldClock ‐ rapid protocol protyping with google Protocol Buffers integration
HTTP
  • Snoop ‐ build your own extremely light-weight HTTP client and server
  • File server ‐ asynchronous large file streaming in HTTP
  • Web Sockets (Client & Server) ‐ add a two-way full-duplex communication channel to HTTP using Web Sockets
  • SPDY (Client & Server) ‐ implement SPDY protocol
  • CORS demo ‐ implement cross-origin resource sharing
Advanced
  • Proxy server ‐ write a highly efficient tunneling proxy server
  • Port unification ‐ run services with different protocols on a single TCP/IP port
UDT
  • Byte streams ‐ use UDT in TCP-like byte streaming mode
  • Message flow ‐ use UDT in UDP-like message delivery mode
  • Byte streams in symmetric peer-to-peer rendezvous connect mode
  • Message flow in symmetric peer-to-peer rendezvous connect mode
我们的分析从这里开始,netty是client-server形式的,我们以最简单的discard示例开始,其服务器端代码如下:
/** * Discards any incoming data. */public final class DiscardServer { static final boolean SSL = System.getProperty("ssl") != null; static final int PORT = Integer.parseInt(System.getProperty("port", "8009")); public static void main(String[] args) throws Exception { // Configure 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) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } p.addLast(new DiscardServerHandler()); } }); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to gracefully // shut down your server. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }}上面的代码中使用了下面几个类:
1. EventLoopGroup
实现类为NioEventLoopGroup,其层次结构为:
从netty-example分析Netty组件

文章插图
 
EventExecutorGroup为所有类的父接口,它通过next()方法来提供EventExecutor供使用 。除此以外,它还负责处理它们的生命周期,允许以优雅的方式关闭 。
EventExecutor是一种特殊的EventExcutorGroup,它提供了一些便利的方法来查看一个线程是否在一个事件循环中执行过,除此以外,它也扩展了EventExecutorGroup,从而提供了一个通用的获取方法的方式 。
EventLoopGroup是一种特殊的EventExcutorGroup,它提供了channel的注册功能,channel在事件循环中将被后面的selection来获取到 。
NioEventLoopGroup继承自MultithreadEventLoopGroup,基于channel的NIO selector会使用该类 。
【从netty-example分析Netty组件】2.ServerBootstrap使ServerChannel容易自举 。
group(EventLoopGroup parentGroup, EventLoopGroup childGroup)方法设置父EventLoopGroup和子EventLoopGroup 。这些EventLoopGroup用来处理所有的事件和ServerChannel和Channel的IO 。
channel(Class<? extends C> channelClass)方法用来创建一个Channel实例 。创建Channel实例要不使用此方法,如果channel实现是无参构造要么可以使用channelFactory来创建 。
handler(ChannelHandler handler)方法,channelHandler用来处理请求的 。


推荐阅读