本文共 8796 字,大约阅读时间需要 29 分钟。
Netty权威指南中以时间服务器为入门案例,演示了如何通过Netty完成了服务端与客户端之间的交互过程。
在开始使用Netty开发之前,先回顾一下使用NIO进行服务端开发的步骤。
一个简单的NIO服务端程序,如果我们直接使用JDK的NIO类库进行开发,竟然需要经过烦琐的十多步操作才能完成最基本的消息发送和读取,下面我们看看使用Netty是如何轻松搞定服务端开发的。
import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;public class TimeServer { public void bind(int port) throws InterruptedException { /* 创建两个线程组,boss用于处理客户端连接事件,worker用于处理读写请求。 NioEventLoopGroup可以包含多个NIO线程,专门用于网络事件的处理,实际上它们就是Reactor线程组。 */ EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { /* ServerBootstrap是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度。 */ ServerBootstrap bootstrap = new ServerBootstrap(); /* bootstrap.group(boss, worker)把两个线程组传递到ServerBootstrap 中 */ bootstrap.group(boss, worker) /* 创建Channel为NioServerSocketChannel,它的功能对应JDK NIO类库中的ServerSocketChannel */ .channel(NioServerSocketChannel.class) /* 配置TCP参数 */ .option(ChannelOption.SO_BACKLOG, 1024) /* 添加handler处理类,直接创建匿名内部类,重写initChannel方法, 它的作用类似于Reactor模式中的Handler类, 主要用于处理网络I/O事件,例如记录日志、对消息进行编解码等。 */ .childHandler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new TimeServerHandler()); } }); /* 调用bind绑定端口,并调用sync同步阻塞直到绑定操作完成,完成之后返回一个ChannelFuture, ChannelFuture主要用于异步操作的通知回调 */ ChannelFuture future = bootstrap.bind(port).sync(); /* 等待服务端链路关闭之后main函数才退出。 */ future.channel().closeFuture().sync(); } finally { /* 调用NIO线程组的shutdownGracefully进行优雅退出,它会释放跟shutdownGracefully相关联的资源。 */ boss.shutdownGracefully(); worker.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { new TimeServer().bind(8080); }}
import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import java.util.Date;/** * TimeServerHandler继承自ChannelInboundHandlerAdapter,主要用于对网络事件进行读写操作, * 通常我们只需要关注channelRead和exceptionCaught方法 */public class TimeServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { /* 类型转换,把msg转成Netty的ByteBuf对象,ByteBuf对象类似于JDK NIO中的ByteBuffer对象, 但是Netty的ByteBuf更加强大和灵活。 */ ByteBuf buf = (ByteBuf) msg; /* buf.readableBytes()可以获取buf中的可读的字节数, 然后根据可读的字节数创建byte数组 */ byte[] req = new byte[buf.readableBytes()]; /* 通过ByteBuf的readBytes方法把buf中的字节数组赋值到新的byte数组中 */ buf.readBytes(req); /* 构建字符串 */ String body = new String(req, "UTF-8"); System.out.println("The time server receive order : " + body); /* 判断消息内容是否是"QUERY TIME ORDER",如果是查询服务器当前时间,否则返回错误"BAD ORDER" */ String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; /* 通过Unpooled.copiedBuffer创建一个ByteBuf对象 */ ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); /* 通过ChannelHandlerContext的write方法发送消息给客户端 */ ctx.write(resp); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { /* 将消息发送队列中的消息写入到SocketChannel中发送给对方。 从性能角度考虑,为了防止频繁的唤醒Selector进行消息发送,Netty的write方法并不直接将消息写入SocketChannel中, 调用write方法只是把待发送的消息放到发送缓冲数组中,再通过调用flush方法,将发送缓冲区的消息全部写到SocketChannel中 */ ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { /* 当发送异常时,关闭ChannelHandlerContext,释放和ChannelHandlerContext相关联的句柄等资源 */ ctx.close(); }}
import io.netty.bootstrap.Bootstrap;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class TimeClient { public void connect(int port, String host) throws InterruptedException { /* 创建处理I/O读写的NioEventLoopGroup线程组 */ EventLoopGroup group = new NioEventLoopGroup(); try { /* 创建客户端辅助启动类Bootstrap */ Bootstrap bootstrap = new Bootstrap(); /* 把NioEventLoopGroup传递到Bootstrap中 */ bootstrap.group(group) /* 创建NioSocketChannel,它的功能对应JDK NIO类库中的SocketChannel */ .channel(NioSocketChannel.class) /* 配置TCP参数 */ .option(ChannelOption.TCP_NODELAY, true) /* 添加handler处理类,直接创建匿名内部类,重写initChannel方法, 其作用是当创建NioSocketChannel成功之后,在进行初始化时, 将它的ChannelHandler设置到ChannelPipeline中,用于处理网络I/O事件 */ .handler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeClientHandler()); } }); /* 调用connect方法异步连接,然后调用同步方法等待连接成功。 */ ChannelFuture future = bootstrap.connect(host, port).sync(); /* 当客户端连接关闭之后,客户端主函数退出,退出之前释放NIO线程组的资源 */ future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { int port = 8080; new TimeClient().connect(port, "127.0.0.1"); }}
import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;public class TimeClientHandler extends ChannelInboundHandlerAdapter { private final ByteBuf firstMessage; /** * 构建"QUERY TIME ORDER" */ public TimeClientHandler() { byte[] req = "QUERY TIME ORDER".getBytes(); firstMessage = Unpooled.buffer(req.length); firstMessage.writeBytes(req); } /** * 当客户端和服务端TCP链路建立成功后,Netty的NIO线程会调用channelActive方法,并发送firstMessage内容给服务端 * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(firstMessage); } /** * 当服务端返回应答消息时,channelRead方法被调用 * @param ctx * @param msg * @throws Exception */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { /* msg转成Netty的ByteBuf并从中读取服务端发送的消息内容。 */ 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); } /** * 当发送异常时,关闭ChannelHandlerContext,释放和ChannelHandlerContext相关联的句柄等资源 * @param ctx * @param cause * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); }}
本文演示了Netty的入门应用,通过使用Netty完成了时间服务器程序,可以发现相比于传统的NIO程序,Netty的代码更加简洁、开发难度更低、扩展性也更好,非常适合作为基础通信框架被用户集成和使用。
转载地址:http://iqlrb.baihongyu.com/