Netty入门应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shenchaohao12321/article/details/88579395

1、Netty时间服务器服务端 TimeServer

package com.phei.netty.basic;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author lilinfeng
 * @version 1.0
 * @date 2014年2月14日
 */
public class TimeServer {

    public void bind(int port) throws Exception {
        // 配置服务端的NIO线程组
        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 ChildChannelHandler());
            // 绑定端口,同步等待成功
            ChannelFuture f = b.bind(port).sync();

            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel arg0) throws Exception {
            arg0.pipeline().addLast(new TimeServerHandler());
        }

    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        new TimeServer().bind(port);
    }
}

我们从bind方法开始学习,在代码第20~21行创建了两个 NioEventLoopGroup实例。NioEventLoopGroup是个线程组,它包含了一组NIO线程,专门用于网络事件的处理,实际上它们就是 Reactor线程组。这里创建两个的原因是一个用于服务端接受客户端的连接另一个用于进行 Socketchannel的网络读写。第23行创建 Server bootstrap对象,它是 Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度。第24行调用Server Bootstrap的 group方法,将两个NO线程组当作入参传递到 Server Bootstrap中。接着设置创建的 Channel为 NioServerSocketchannel,它的功能对应于 JDK NIO类库中的ServerSocketChannel类。然后配置 NioServerSocketChannel的TCP参数,此处将它的 backlog设置为1024,最后绑定LO事件的处理类 Childchannelhandler,它的作用类似于 Reactor模式中的 Handler类,主要用于处理网络IO事件,例如记录日志、对消息进行编解码等服务端启动辅助类配置完成之后,调用它的bind方法绑定监听端口,随后,调用它的同步阻塞方法sync等待绑定操作完成。完成之后Net!会返回一个 Channelfuture,它的功能类似于JDK的 java.util.concurrent.Future,主要用于异步操作的通知回调。第32行使用f.channel().closeFuture().sync()方法进行阻塞,等待服务端链路关闭之后main函数才退出。
第34~36行调用NIO线程组的 shutdownGracefully进行优雅退出,它会释放跟shutdownGracefully相关联的资源。
下面看看 TimeServerHandler类是如何实现的。

package com.phei.netty.basic;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author lilinfeng
 * @version 1.0
 * @date 2014年2月14日
 */
public class TimeServerHandler extends ChannelHandlerAdapter {

    @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("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) {
        ctx.close();
    }
}

TimeServerHandler继承自ChannelHandlerAdapter,它用于对网络事件进行读写操作,通常我们只需要关注 channelRead和exceptionCaught方法。下面对这两个方法进行简单说明。
第17行做类型转换,将msg转换成Netty的 ByteBuf对象。 ByteBuf类似于JDK中的Java.nio.ByteBuffer对象,不过它提供了更加强大和灵活的功能。通过 ByteBuf的readableBytes方法可以获取缓冲区可读的字节数,根据可读的字节数创建byte数组,通过ByteBuf的 readBytes方法将缓冲区中的字节数组复制到新建的byte数组中,最后通过new String构造函数获取请求消息。这时对请求消息进行判断,如果是" QUERY TIME ORDER"则创建应答消息,通过 ChannelHandlerContext的 write方法异步发送应答消息给客户端。
第30行我们发现还调用了 ChannelHandlerContext的fush方法,它的作用是将消息发送队列中的消息写入到 Socketchannel中发送给对方。从性能角度考虑,为了防止频繁地唤醒 Selector进行消息发送,Netty的 write方法并不直接将消息写入 SocketChannel中,调用 write方法只是把待发送的消息放到发送缓冲数组中,再通过调用flush方法,将发送缓冲区中的消息全部写到 Socketchannel中。
第35行,当发生异常时,关闭 ChannelhandlerContext,释放和 ChannelhandlerContext相关联的句柄等资源通过对代码进行统计分析可以看出,不到30行的业务逻辑代码,即完成了NIO服务端的开发,相比于传统基于 JDK NIO原生类库的服务端,代码量大大减少,开发难度也降低了很多。

2、Netty时间服务器客户端TimeClient

package com.phei.netty.basic;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author lilinfeng
 * @version 1.0
 * @date 2014年2月14日
 */
public class TimeClient {

    public void connect(int port, String host) throws Exception {
        // 配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new TimeClientHandler());
                        }
                    });

            // 发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();

            // 当代客户端链路关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放NIO线程组
            group.shutdownGracefully();
        }
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        new TimeClient().connect(port, "127.0.0.1");
    }
}

我们从 connect方法讲起,在第20行首先创建客户端处理O读写的 NioEventLoopGroup线程组,然后继续创建客户端辅助启动类 Bootstrap,随后需要对其进行配置。与服务端不同的是,它的 Channel需要设置为 NioSocketChannel,然后为其添加 Handler。此处
为了简单直接创建匿名内部类,实现 unicHannel方法,其作用是当创建 NioSocketChannel成功之后,在进行初始化时,将它的 ChannelHandler设置到 ChannelPipeline中,用于处理网络IO事件。客户端启动辅助类设置完成之后,调用 connect方法发起异步连接,然后调用同步方法等待连接成功。最后,当客户端连接关闭之后,客户端主函数退出,退出之前释放NIO线程组的资源。
下面我们继续看 TimeClientHandler的代码如何实现。

package com.phei.netty.basic;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.logging.Logger;

/**
 * @author lilinfeng
 * @version 1.0
 * @date 2014年2月14日
 */
public class TimeClientHandler extends ChannelHandlerAdapter {

    private static final Logger logger = Logger
            .getLogger(TimeClientHandler.class.getName());

    private final ByteBuf firstMessage;

    /**
     * Creates a client-side handler.
     */
    public TimeClientHandler() {
        byte[] req = "QUERY TIME ORDER".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(firstMessage);
    }

    @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) {
        // 释放资源
        logger.warning("Unexpected exception from downstream : "
                + cause.getMessage());
        ctx.close();
    }
}

这里重点关注三个方法: channelActive、 channelRead和 exceptionCaught。当客户端和服务端TCP链路建立成功之后,Netty的NlO线程会调用 channelActive方法,发送查询时间的指令给服务端,调用 ChannelHandlerContext的 writeAndFlush方法将请求消息发送给服务端。当服务端返回应答消息时, channelRead方法被调用,第39~43行从Netty的 ByteBuf中读取并打印应答消息。
第47~52行,当发生异常时,打印异常日志,释放客户端资源。
 

猜你喜欢

转载自blog.csdn.net/shenchaohao12321/article/details/88579395