Netty学习笔记二-Netty入门开发

上一节中介绍的java NIO的开发,回顾下NIO开发的步骤:
1、创建ServerSocketChannel并设置为非阻塞模式
2、绑定监听端口
3、创建多路服务器Selector,将创建的ServerSocketChannel注册到Selector,监听SelectKey.Accept事件
4、创建IO线程轮询Selector.select
5、如果轮询到就绪的Channel如果是OP_ACCEPT状态说明是新的客户端接入则调用ServerSocketChannel.accept方法接受新的客户端
6、设置客户端链路SocketChannel为非阻塞模式,并且将其注册到Selector上,监听SelectKey.OP_READ操作位
7、如果轮询到Channel为OP_READ,则说明SocketChannel中有新的就绪的数据包需要读取,则通过ByteBuffer读取数据
由上来看,直接通过Java原生的类进行NIO编程非常复杂繁琐,而Netty正好解决了这个难题
下面通过一个简单的Netty程序了解Netty开发
netty服务端代码:

public class TimeServer {
    public void bind(int port) throws Exception {
        //创建两个线程组 一个用于服务端接收客户端的连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //一个用于网络读写
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChildChannelHander());
            ChannelFuture future = b.bind(port).sync();
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHander extends ChannelInitializer {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args) {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {

            }
        }
        try {
            new TimeServer().bind(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class TimeServerHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception{
        ByteBuf byteBuf = (ByteBuf)msg;
        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);
        String body = new String(req,"UTF-8");
        System.out.println("the time server receive order:"+body);
        String currentTIme = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
            System.currentTimeMillis()
        ).toString():"BAD ORDER";
        ByteBuf resp = Unpooled.copiedBuffer(currentTIme.getBytes());
        ctx.write(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

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

}

程序刚开始创建了两个EventLoopGroup线程,一个专门监听服务端接收客户端请求,一个专门处理业务逻辑,之后创建一个ServerBootstrap类,并将线程组传递到ServerBootstrap,设置的Channel为NioServerSocketChannel并将事件处理类设置为ChildChannelHander,最后调用bind方法绑定监听端口,最后future.channel().closeFuture().sync()会阻塞直到服务端断开连接
客户端代码:

public class TimeClient {
    public void connect(int port,String host) throws Exception {
        //创建读写io线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        System.out.println("1");
                        socketChannel.pipeline().addLast(new TimeClientHandler());
                    }
                });
            System.out.println("2");
            ChannelFuture f = b.connect(host,port).sync();
            System.out.println("3");
            f.channel().closeFuture().sync();
            System.out.println("4");
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = 8080;
        if (args != null && args.length >0) {
            try {
                port = Integer.valueOf(args[0]);
            }catch (NumberFormatException e) {

            }
        }
        try {
            new TimeClient().connect(port,"127.0.0.1");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Netty客户端代码更为简单,第一步创建NioEventLoopGroup线程组,跟服务端一样再创建客户端辅助类Bootstrap并将线程组和渠道作为参数出传入,并且指定handler实现initChannel方法,其作用就是当创建NioSocketChannel之后回调initChannel方法处理网络IO事件
下面是TimeChientHander代码

public class TimeClientHandler extends ChannelHandlerAdapter {
    private final ByteBuf firstMsg;

    public TimeClientHandler() {
        byte[] req = "QUERY TIME ORDER".getBytes();
        firstMsg = Unpooled.buffer(req.length);
        firstMsg.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(firstMsg);

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req,"UTF-8");
        System.out.println("Now is : "+body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("Unexpected exception from downstream :"+cause.getMessage());
        ctx.close();
    }
}

TimeChientHander实现了channelActive,channelRead,exceptionCaught方法,
channelActive为客户端或者服务端TCP链路建立连接之后回调,当服务端写数据到客户端时channelRead回调,当发生异常时会回调exceptionCaught方法。

从上面代码可以看出Netty将IO事件的处理抽象为ChannelHandler接口,开发者可以继承ChannelHandler接口来自定义事件处理逻辑。
ChannelHandler接口主要有以下方法:
channelRegistered(ChannelHandlerContext ctx) 注册到EventLoop成功回调
channelActive(ChannelHandlerContext ctx) 当建立连接后回调
channelRead(ChannelHandlerContext ctx, Object msg) 当前channel读到数据时回调
channelReadComplete(ChannelHandlerContext ctx) 读取数据完成后回调
exceptionCaught(ChannelHandlerContext ctx, Throwable cause) 发生异常时回调

在实际Netty开发中基本都是继承ChannelHandler实现业务逻辑

在初始化Channel时需要将自定义的ChannelHandler添加到该Channel上,Netty实现是ChannelPipeline.addLast
源码如下

public interface ChannelPipeline extends Iterable> {
……
}

其中继承Iterable迭代器接口,可以看出其hannelPipeline是一系列ChannelHandler的集合(可以理解为链表)自定义的ChannelHandler可以调用它的addFirst、addLast添加到IO处理pipeLine的头或者尾
主要方法有以下:
ChannelPipeline addFirst(String name, ChannelHandler handler) 将handler插入到handler链表头部
ChannelPipeline addLast(ChannelHandler... handlers) 将handler插入到handler链表尾部
自动以的ChannelHandler一般通过上述方法添加到事件处理链表中

你可能感兴趣的:(Netty学习笔记二-Netty入门开发)