首先回顾一下用NIO开发TimeServer的步骤:
1.创建ServerSocketChannel,配置为非阻塞模式;
2.绑定监听,配置TCP参数,比如backlog大小;
3.创建一个独立的IO线程,用于轮询多路复用器Selector;
4.创建Selector,将之前创建的ServerSocketChannel注册到Selector上,监听SelectionKey.OP_ACCEPT;
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服务器端程序如果用JDK的NIO类库进行开发,则需要以上的10多个步骤才能完成消息的发送和读取,这也是我们为什么选择用Netty或者其他NIO框架进行开发的原因。
下面用Netty实现时间服务器
1.服务器端代码
package com.yy.test.netty;
import java.util.Date;
import org.apache.log4j.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
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;
public class TimeServer {
static Logger logger = Logger.getLogger(TimeServer.class);
public void bind(int port) throws Exception{
//配置NIO服务器端线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap server = new ServerBootstrap();
server.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new childHandler());
//绑定端口。同步等待
ChannelFuture channelFuture = server.bind(port).sync();
//等待服务器端监听端口关闭
channelFuture.channel().closeFuture().sync();
}finally{
bossGroup.shutdownGracefully();//优雅的退出,释放NIO线程组
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
try {
new TimeServer().bind(8085);
} catch (Exception e) {
logger.error("TimeServer.main error:",e);
}
}
}
class childHandler extends ChannelInitializer<socketchannel>{
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler());
}
}
class TimeServerHandler extends ChannelHandlerAdapter{
static Logger logger = Logger.getLogger(TimeServerHandler.class);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String content = new String(bytes,"utf-8");
System.out.println("The server received "+content);
String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(content) ? new Date(System.currentTimeMillis()).toString():"BAD QUERY";
ByteBuf writeBuf = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(writeBuf);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
2.客户端代码
package com.yy.test.netty;
import java.net.InetSocketAddress;
import org.apache.log4j.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class TimeClient {
static Logger logger = Logger.getLogger(TimeClient.class);
public void connect(String host,int port) throws Exception{
//配置NIO客户端线程组
NioEventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap client = new Bootstrap();
client.group(group)
.option(ChannelOption.TCP_NODELAY, true)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<socketchannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler());
}
});
//发起异步连接请求
ChannelFuture channelFuture = client.connect(new InetSocketAddress(host, port)).sync();
//等待客户端链路关闭
channelFuture.channel().closeFuture().sync();
}finally{
group.shutdownGracefully();//优雅的退出,释放NIO线程组
}
}
public static void main(String[] args) {
try {
new TimeClient().connect("127.0.0.1", 8085);
} catch (Exception e) {
logger.error("TimeClient.main error:",e);
}
}
}
class TimeClientHandler extends ChannelHandlerAdapter{
static Logger logger = Logger.getLogger(TimeClientHandler.class);
private ByteBuf buffer;
public TimeClientHandler(){
byte[] bytes = "QUERY TIME ORDER".getBytes();
buffer = Unpooled.buffer(bytes.length);
buffer.writeBytes(bytes);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(buffer);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf)msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String body = new String(bytes,"utf-8");
logger.info("Now is "+body);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("TimeClientHandler.error:",cause);
ctx.close();
}
}
3.运行结果
通过用Netty重构时间服务器程序,可以发现相比于传统的NIO程序,Netty的代码更加简洁、开发难度更低、拓展度也更好,非常适合作为基础通信框架被用户集成和使用。