Netty combat

A, Netty asynchronous and event-driven
1.Java network programming review
socket.accept blocking
socket.setsockopt / non-blocking
2.NIO asynchronous non-blocking
a) .nio using the selector (java.nio.channels.Selector when key non-blocking) achieved; may monitor the completion status of the plurality of socket reader to coordinate reading and writing of the other socket, to improve resource utilization;
B) an asynchronous event-driven, initiated request socket, immediate response, backend processing request, notification processed. client;
vector c) connecting the link .Channel entity, requests and responses; Netty callback to handle events, time-triggered -> ChannelHandler-> channelActive () to process the event;
D) to listen .ChannelFuture by providing event notification ChannelFutureListener completion of the processing result; Future is the need to manually obtain the result; each I / O operation will return a ChannelFuture immediately, without blocking, background processing I / O, as to when the processing is completed, the driving time asynchronous notification;
3.Nttey of asynchronous become a model based on Future and callback above, and then distributed to over ChannelHandler time for processing;

二、Netty Demo
1.EchoServerHandler

package chap01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg){
        ByteBuf in = (ByteBuf) msg;
        System.out.println("Server received: "+ in.toString(CharsetUtil.UTF_8));
        ctx.write(in);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        cause.printStackTrace();
        ctx.close();
    }
}

2.EchoServer

package chap01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {
    private final int port;

    public  EchoServer(int port){
        this.port = port;
    }

    public static void main(String[] args) throws  Exception{
//        if (args.length !=-1){
//            System.err.println("Usage: " + EchoServer.class.getSimpleName()+"<port>");
//        }
//        int port = Integer.parseInt(args[0]);
//        new EchoServer(port).start();
        new EchoServer(9001).start();
    }

    public void start() throws Exception{
        final  EchoServerHandler serverHandler = new EchoServerHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>(){
               @Override
               public void initChannel(SocketChannel ch) throws Exception{
                   ch.pipeline().addLast(serverHandler);
               }
            });
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }
    }
}

 3.EchoClientHandler

package chap01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    public void channelActive(ChannelHandlerContext ctx){
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx,ByteBuf in){
        System.out.println("Client received: "+in.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        cause.printStackTrace();
        ctx.close();
    }

}

4.EchoClient

package chap01;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

public class EchoClient {
    private final String host;
    private final int port;

    public EchoClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host,port)).handler(new ChannelInitializer<SocketChannel>(){
               @Override
               public void initChannel(SocketChannel ch) throws Exception{
                   ch.pipeline().addLast(new EchoClientHandler());
               }
            });
            ChannelFuture f = b.connect().sync();
        }finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws  Exception{
//        if (args.length!=2){
//            System.err.println("Usage: "+EchoClient.class.getSimpleName() + "<host><port>");
//                    return;
//        }
//        String host = args[0];
//        int port = Integer.parseInt(args[1]);
//        new EchoClient(host,port).start();
        new EchoClient("127.0.0.1",9001).start();
    }
}

 

Guess you like

Origin www.cnblogs.com/therunningfish/p/10959225.html