Netty (二) 入门

来源:互联网 发布:手游云挂机软件 编辑:程序博客网 时间:2024/06/05 15:32

在上篇《Netty(一)引题》中,分别对AIO,BIO,PIO,NIO进行了简单的阐述,并写了简单的demo。但是这里说的简单,我也只能呵呵了,特别是NIO、AIO(我全手打的,好麻烦)。
在开始netty开发TimeServer之前,先回顾下NIO进行服务端开发的步骤:

  • 1.创建ServerSocketChannel,配置它为非阻塞;
  • 2.绑定监听,配置TCP参数,如backlog大小;
  • 3.创建独立的IO线程,用于轮询多路复用器Selector;
  • 4.创建Selector,将之前创建的ServerSocketChannel注册到Selector上,监听SelectionKey.ACEPT;
  • 5.启动IO线程,在循环体中执行Selector.select()方法,轮询就绪的Channel;
  • 6.当轮询到处于就绪状态的Channel时,需要对其进行判断,如果是OP_ACCEPT状态,说明是新的客户端接入,则调用ServerSocketChannel.accept()方法接受新的客户端;
  • 7.设置新接入的客户端链接SocketChannel为非阻塞模式,配置其他的一些TCP参数;
  • 8.将SocketChannel注册到Selector,监听OP_READ操作位;
  • 9.如果轮询的Channel为OP_READ,则说明SocketChannel中有新的就绪的数据包需要读取,则构造ByteBuffer对象,读取数据包;
  • 10.如果轮询的Channel为OP_WRITE,说明还有数据没有发送完成,需要继续发送。

一个简单的NIO程序,需要经过繁琐的十多步操作才能完成最基本的消息读取和发送,这也是我学netty的原因,下面就看看使用netty是如何轻松写服务器的。
在这里,我使用IDEA 14 + Maven用netty写上篇中TimeServer的程序。这里我直接用Maven的pom.xml来直接下载netty的包(Maven是对依赖进行管理,支持自动化的测试、编译、构建的项目管理工具,具体的Maven请读者自行百度、google搜索)。

服务端:

TimeServer.java

package nettytest.timeserver;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;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 时间服务器 * Created by Lovell on 30/09/2016. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class TimeServer {    private static Logger logger = LoggerFactory.getLogger(TimeServer.class);    public void bind(int port) throws Exception {        // 配置服务端的NIO线程组        // NioEventLoopGroup类是个线程组,包含一组NIO线程,用于网络事件的处理        // (实际上他就是Reactor 线程组)        // 创建2个线程组, 1个是服务端接收客户端的连接,        // 另一个是进行SocketChannel的网络读写        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            // ServerBootstrap 类, 是启动NIO服务器的辅助启动类            ServerBootstrap serverBootstrap = new ServerBootstrap();            serverBootstrap.group(bossGroup, workerGroup)                    .channel(NioServerSocketChannel.class)  // NIO Socket管道                    .option(ChannelOption.SO_BACKLOG, 1024) // 握手成功缓存大小                    .option(ChannelOption.SO_KEEPALIVE, true) // 2小时无数据激活心跳机制                    .childHandler(new ServerChannelHandler());            /**             * 这个都是socket的标准参数,并不是netty自己的。             * 具体为:             * ChannelOption.SO_BACKLOG, 1024             * BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度。             * 如果未设置或所设置的值小于1,Java将使用默认值50。             * ChannelOption.SO_KEEPALIVE, true             * 是否启用心跳保活机制。在双方TCP套接字建立连接后(即都进入ESTABLISHED状态)并且在两个小时左右上层没有任何数据传输的情况下,             * 这套机制才会被激活。             * ChannelOption.TCP_NODELAY, true             * 在TCP/IP协议中,无论发送多少数据,总是要在数据前面加上协议头,同时,对方接收到数据,也需要发送ACK表示确认。             * 为了尽可能的利用网络带宽,TCP总是希望尽可能的发送足够大的数据。             * 这里就涉及到一个名为Nagle的算法,该算法的目的就是为了尽可能发送大块数据,避免网络中充斥着许多小数据块。             * TCP_NODELAY就是用于启用或关于Nagle算法。如果要求高实时性,有数据发送时就马上发送,就将该选项设置为true关闭Nagle算法;             * 如果要减少发送次数减少网络交互,就设置为false等累积一定大小后再发送。默认为false。             */            // 绑定端口,同步等待成功            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();            // 等待服务端监听端口关闭            channelFuture.channel().closeFuture().sync();        } finally {            // 释放线程池资源            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }    private class ServerChannelHandler extends ChannelInitializer<SocketChannel> {        @Override        protected void initChannel(SocketChannel ch) throws Exception {            ch.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 ex) {            }        }        new TimeServer().bind(port);    }}

TimeServerHandler.java

package nettytest.timeserver;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.Date;/** * Created by Lovell on 30/09/2016. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class TimeServerHandler extends SimpleChannelInboundHandler {    private static Logger logger = LoggerFactory.getLogger(TimeServerHandler.class);    // 用于网络的读写操作    @Override    protected void channelRead0(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 order : " + body);        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new 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();        // 它的作用是把消息发送队列中的消息写入SocketChannel中发送给对方        // 为了防止频繁的唤醒Selector进行消息发送,Netty的write方法,并不直接将消息写入SocketChannel中        // 调用write方法只是把待发送的消息发到缓冲区中,再调用flush,将发送缓冲区中的消息        // 全部写到SocketChannel中。    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {        super.exceptionCaught(ctx, cause);        ctx.close();    }}

客户端:

TimeClient.java

package nettytest.timeserver;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;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Created by Lovell on 30/09/2016. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class TimeClient {    private static Logger logger = LoggerFactory.getLogger(TimeClient.class);    public void connect(String host,int port)throws Exception{        // 配置服务端的NIO线程组        EventLoopGroup group = new NioEventLoopGroup();        try {            // Bootstrap 类,是启动NIO服务器的辅助启动类            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 {            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 ex){}        }        new TimeClient().connect("127.0.0.1",port);    }}
TimeClientHandler.java

package nettytest.timeserver;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Created by Lovell on 30/09/2016. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class TimeClientHandler extends SimpleChannelInboundHandler{    private static Logger logger = LoggerFactory.getLogger(TimeClientHandler.class);    // 写日志    private final ByteBuf firstMessage;    public TimeClientHandler(){        byte[] req = "QUERY TIME ORDER".getBytes();        firstMessage = Unpooled.buffer(req.length);        firstMessage.writeBytes(req);    }    @Override    protected void channelRead0(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 channelActive(ChannelHandlerContext ctx){        // 当客户端和服务端建立tcp成功之后,Netty的NIO线程会调用channelActive        // 发送查询时间的指令给服务端。        // 调用ChannelHandlerContext的writeAndFlush方法,将请求消息发送给服务端        // 当服务端应答时,channelRead方法被调用        ctx.writeAndFlush(firstMessage);    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){        logger.warn("message from:"+cause.getMessage());        ctx.close();    }}

本例子没有考虑读半包的处理,对于功能演示和测试,本例子没问题,但是如果进行性能或者压力测试,就不能正常工作了。在下一节会弄正确处理半包消息的例子。

项目在源码在src/main/java/Netty/下,分为客户端和服务端。

源码下载:GitHub地址:https://github.com/orange1438/Netty_Course

题外话:虽然文章全是我纯手打,没任何复制,但是文章大多数内容来自《Netty权威指南》,我也是顺便学习的。之前我做C++服务端,因为狗血的面试C++,结果公司系统居然是java的,无耐我所在的重庆,C++少得可怜,所以只有在公司里学java了。当然,有epoll,select,事件驱动,TCP/IP概念的小伙伴来说,学这个netty,还是挺简单的。

 
作者:orange1438出处:http://www.cnblogs.com/orange1438/本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

来自:http://www.cnblogs.com/orange1438/p/5003080.html
0 0