DOCX

From the netty - example analysis netty component

By Katie Rice,2015-12-04 15:04
16 views 0
From the netty - example analysis netty component

    From the netty - example analysis netty component Analysis of nettystarting from the source

    Preparation:

    1. Download the source: https://github.com/netty/netty.git I download version 4.1

    2. The eclipse import maven project.

    Netty provides a netty - example project,

    Our analysis from here, netty is in the form of the client - server, we begin with the

    simplest example the discard the server-side code is as follows:

/**

     * 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 () {

     @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();

     }

     }

    }

    The code above USES the following categories:

    1. EventLoopGroup

    The implementation class for NioEventLoopGroup, its hierarchy is: