Demo Netty learning to build

  As shown below, we write a simple Netty Demo, to achieve the client and server communicate.

  1, Netty server startup class

/**
 Main * (1), for the initialization of Acceptor "thread pool" and for I / O from the work "thread pool";
 * (2), initialization ServerBootstrap instance, which is the server application development netty inlet;
 * (3), by the method ServerBootstrap group is provided (1) in a master-slave initialization 'thread pool ";
 * (4), the specified channel channel type, because the service side, is therefore NioServerSocketChannel;
 * (5), provided ServerSocketChannel processor
 * (6), set up sub-channel is SocketChannel processor, which is the actual internal business development, "the main battlefield"
 * (8), sub-channel configuration option is SocketChannel
 * (9), bind and listen for a port
 */

public class SimpleNettyServer {

    public void bind(int port) throws Exception {

        // server-side applications using two NioEventLoopGroup create two EventLoop groups, EventLoop this is equivalent to a processing thread is Netty receiving a request processing threads and IO requests.
        // main thread group, for accepting a client connection, but no treatment, just like the boss, do not do things 
        EventLoopGroup bossGroup = new new NioEventLoopGroup ();
         // the thread group, when the boss accepts the connection and the connection to the registration accepted worker, the processing flow connection is accepted. 
        WorkerGroup = EventLoopGroup new new NioEventLoopGroup ();

        the try {
             // Create a class netty server startup, auxiliary tools, for a range of channel configuration server 
            of ServerBootstrap ServerBootstrap = new new of ServerBootstrap ();
             / **
             * Use the number of threads, and how to map them to channel created depends EventLoopGroup achieve, or even can be configured by the constructor.
             * Set loop thread group, the former for the client connection event process, which is used for processing network IO (server using the two parameters)
             * public ServerBootstrap group(EventLoopGroup group)
             * public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup)
             * / 
            ServerBootstrap.group (bossGroup, workerGroup)            // bind two thread groups
                     // for constructing plant socketchannel 
                    .Channel (NioServerSocketChannel. Class )    // specified pattern NIO 
                    / **
                     * @Description: initializer, the channel registration, performs the appropriate initialization methods inside, passing custom client Handle (the server where the operation)
                     *
                     @Override
                     protected void initChannel(SocketChannel channel) throws Exception {
                     // to obtain a corresponding conduit through SocketChannel
                     ChannelPipeline pipeline = channel.pipeline();

                     // through the pipeline, adding handler
                     pipeline.addLast("nettyServerOutBoundHandler", new NettyServerOutBoundHandler());
                     pipeline.addLast("nettyServerHandler", new NettyServerHandler());
                     }
                      * Sub-processor may also be implemented by the following internal method.
                     */
                    .childHandler(new ChannelInitializer<SocketChannel>() {  // 子处理器,用于处理workerGroup
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
//                            socketChannel.pipeline().addLast(new NettyServerOutBoundHandler());
                            socketChannel.pipeline().addLast(new SimpleNettyServerHandler());

                        }
                    });

            // start server, port bindings, starts receiving incoming connections, set to start port number 8088, while for the synchronous start 
            ChannelFuture ChannelFuture = serverBootstrap.bind (8088 ) .sync ();

            System.out.println ( "Start Server" );
             // listens closed channel, wait for the server socket is closed. Set bit synchronous mode 
            channelFuture.channel () closeFuture () sync ( )..;
        } The finally {
             // exit thread group 
            bossGroup.shutdownGracefully ();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new netty.server.SimpleNettyServer().bind(port);
    }

}

  2, Netty server handler class Handler

public class SimpleNettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * This method for reading information transmitted by the client
     *
     * @param ctx
     * @Param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("SimpleNettyServerHandler.channelRead");
        Result ByteBuf = (ByteBuf) MSG;
         byte [] = bytesMsg new new  byte [result.readableBytes ()];
         // MSG ByteBuf type is stored in data, the data is read into the byte [] in 
        result.readBytes (bytesMsg) ;
        ResultStr String = new new String (bytesMsg);
         // receive and print client information 
        System.out.println ( "Client of Said:" + ResultStr);
         // release resources, this line is critical 
        result.release ();

        // send message to the client 
        String Response = "Client Hello!" ;
         // In the current scenario, the transmitted data must be converted into arrays ByteBuf 
        ByteBuf encoded = ctx.alloc () Buffer (*. 4. Response.length ()) ;
        encoded.writeBytes(response.getBytes());
        ctx.write(encoded);
        ctx.flush();
    }

    /**
     * This method is used as the processing exception
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public  void exceptionCaught (CTX ChannelHandlerContext, the cause is the Throwable) throws Exception {
         // When abnormal connection is closed 
        cause.printStackTrace ();
        ctx.close();
    }

    /**
     * After the operation is complete access to information
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

}

  3, Netty client startup class

public class SimpleNettyClient {

    public void connect(String host, int port) throws Exception {
        Worker EventLoopGroup = new new NioEventLoopGroup ();
         the try {
             // the client program to start based 
            on Bootstrap on Bootstrap = new new on Bootstrap ();
             / **
             * EventLoop group
             */
            bootstrap.group(worker);
            /**
             * Factory for construction socketchannel
             * / 
            Bootstrap.channel (NioSocketChannel. Class );
             / ** setup options
             * Parameters: Socket standard parameters of (key, value), self Baidu
             Keep breathing, do not breathe!
             * */
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            /**
             * Custom Client Handle (client thing out here)
             */
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new SimpleNettyClientHandler());
                }
            });

            / ** Open Client monitor connected to the remote node, block waiting until the connection is completed * / 
            ChannelFuture ChannelFuture = bootstrap.connect (Host, Port) .sync ();
             / * block waiting for data, until the channel is closed (Client Close ) * /
            channelFuture.channel().closeFuture().sync();
        } finally {
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        SimpleNettyClient client = new SimpleNettyClient();
        client.connect("127.0.0.1", 8088);

    }

}

  4, the client-based Handler

public class SimpleNettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * This method for receiving a message sent from the server
     *
     * @param ctx
     * @Param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("SimpleClientHandler.channelRead");
        ByteBuf result = (ByteBuf) msg;
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        System.out.println("Server said:" + new String(result1));
        result.release();
    }

    /**
     * This method is used to handle exceptions
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public  void exceptionCaught (CTX ChannelHandlerContext, the cause is the Throwable) throws Exception {
         // When abnormal connection is closed 
        cause.printStackTrace ();
        ctx.close();
    }

    /**
     * This method for transmitting information to the server
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = "hello Server!";
        ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
        encoded.writeBytes(msg.getBytes());
        ctx.write(encoded);
        ctx.flush();
    }

}

  First start the server, and then start the client, respectively, in the Console get the following output:

  Server:

server start
SimpleNettyServerHandler.channelRead
Client said:hello Server!

  Client:

SimpleClientHandler.channelRead
Server said:hello client!

  Thus, a simple Demo Netty i.e. completed structures.

Guess you like

Origin www.cnblogs.com/jing99/p/12515148.html