Netty入门demo

参考代码下载

https://github.com/kangfoo/nettyDefinitiveGuide

1、TimeServer

public class TimeServer {

    private void bind(int port) throws Exception {
        //配置服务端的NIO线程组,用于网络事件的处理,就是Reactor线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //用于进行SocketChannel的网络读写
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //辅助启动类
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    //bocklog为1024:对连接请求的最大队列长度
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //绑定I/O事件的处理类,类似于Reactor模式中的handler类,用于处理I/O事件
                    .childHandler(new ChildChannelHandler());
            //绑定端口,同步等待成功,ChannelFuture用于通知回调
            ChannelFuture f = b.bind(port).sync();

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

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

    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);
    }
}

2、TimeServerHandler

public class TimeServerHandler extends ChannelHandlerAdapter{

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //msg转换为ByteBuf对象
        ByteBuf buf = (ByteBuf) msg;
        //通过readableBytes获取缓冲区可读的字节数
        byte[] req = new byte[buf.readableBytes()];
        //复制到新建的byte数据req中
        buf.readBytes(req);
        //通过new string函数获取请求信息
        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());
        //异步发送应答消息给客户端(将待发送的消息发送缓冲数组中,再调用flush方法全部写入到SocketChannel中)
        ctx.write(resp);
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将消息发送队列中的消息写入到SocketChannel中发送给对方。
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //发生异常时,相关处理
        ctx.close();
    }
}

3、TimeClient

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

        }
    }

    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");
    }
}

4、TimeClientHandler

public class TimeClientHandler extends ChannelHandlerAdapter {

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

    private final ByteBuf firstMessage;

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

    //当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用channelActive方法
    public void channelActive(ChannelHandlerContext ctx) {
        //将请求消息发送给服务端
        ctx.writeAndFlush(firstMessage);
    }

    //当服务端返回应答消息时,该方法被调用
    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);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //释放资源
        logger.warning("Unexpected exception from downstream : " + cause.getMessage());
        ctx.close();
    }
}

相关推荐