1 Netty服务端开发
在开始使用Netty开发TimeServer之前,先回顾一下使用NIO进行访问端开发的步骤。
1、创建ServerSocketChannel,配置为非阻塞模式。
2、绑定监听,配置TCP参数。
3、创建一个独立的I/O线程,用于轮询多路复用器Selector。
4、创建Selector,将之前创建的ServerSocketChannel注册到Selector上,监听SelectionKye.ACCEPT。
5、启动I/O线程,在循环体中执行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个步骤才能完成最基本的消息读取和发送。
TimeServerNetty.java 代码
public class TimeServerNetty {
public static void main(String[] args) {
int port = 8080;
new TimeServerNetty().bind(port);
}
public void bind(int port){
//配置服务端的NIO线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1024)
.childHandler(new ChildChannelHandler());
//绑定端口,同步等待成功
ChannelFuture f = bootstrap.bind(port).sync();
//等待服务端监听端口关闭
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeServerHandlerNetty());
}
}
本篇重点是讲解Netty的应用开发,所以对于一些Netty的类库和用法仅仅做基础性讲解,后续会专门对Netty核心类库和功能进行分析。
代码分析:
首先创建两个NioEventLoopGroup实例。NioEventLoopGroup是个线程组,它包含了一组NIO线程,专门用于网络事件的处理,实际上它们就是Reactor线程组。这里创建两个的原因是一个用于服务端接受客户端的连接,另一个用于进行SocketChannel的网络读写。然后创建BootStrap对象,它是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度。下面调用ServerSocket的grouop方法,将两个NIO线程组当做入参传递到ServerBootstrap中。接着设置创建的Channel位NioServerSocketChannel,它的功能对应于JDK NIO类库中的ServerSocketChannel类。然后配置NioServerSocketChannel的TCP参数,此处把它的backlog设置为1024,最后绑定I/O事件的处理类ChildChannelHandler,它 的作用类似于Reactor模式中的Handler类,主要用于处理网络I/O事件,例如记录日志、对消息进行编解码等。
服务端启动辅助类配置完成之后,调用它的bind方法绑定监听端口,随后,调用它的同步阻塞方法sync等待绑定操作完成。完成之后Netty会返回一个ChannelFuture,它的功能类似于JDK的java.util.concurrent.Future,主要用于异步操作的通知回调。
接着使用f.channel().closeFuture().sync()方法进行阻塞,等待服务端链路关闭之后,main函数才退出。
最后,调用shutdownGracefully退出,它会释放跟shutdownGracefully相关联的资源。
TimeServerHandlerNetty.java 代码
public class TimeServerHandlerNetty extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx,Object msg) throws UnsupportedEncodingException {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String body = new String (bytes,"UTF-8");
System.out.println("TimeServer 接收:" + body);
String currentTime = "query".equalsIgnoreCase(body) ? new
Date(System.currentTimeMillis()).toString() : "bad";
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 t){
ctx.close();
}
}
TimeServerHandlerNetty 继承自 ChannelInboundHandlerAdapter,它用于对网络事件进行读写操作,通常只需要关注channelRead和exceptionCaught方法。
代码分析:ByteBuf类似于JDK中的.java.nio.ByteBuffer对象,不过它提供了更加强大和灵活的功能。通过Bytebuf的readableBytes方法可以获取缓冲区可读的字节数,根据可读的字节数创建byte数组,通过Bytebuf的readBytes方法将缓冲区中的字节数组复制到新建的byte数组中,最后通过new String 构造函数获取请求信息。这时对请求信息进行判断,如果是“query”,则创建应答消息,通过ChannelHandlerContext的write方法异步发送应答消息给客户端。
ctx.flush()方法:它的作用是将发送到队列中的消息写入到SocketChannel中发送给对方。从性能角度考虑,为了防止频繁地唤醒Selector进行消息发送,Netty的write方法并不直接将消息写入SocketChannel中,调用write方法只是把待发送的消息放到发送缓冲区数组中,在通过调用flush方法,将发送缓冲区中的消息全部写到SocketChannel中。
exceptionCaught()方法:当发生异常时,关闭ChannelHandlerContext,释放和ChannelHandlerContext相关联的句柄等资源。
2 Netty客户端开发
TimeClientNetty.java
public class TimeClientNetty {
public void connect(int port,String host) throws Exception{
//配置客户端NIO线程组
NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeClientHandlerNetty());
}
});
//发起同步连接操作
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;
new TimeClientNetty().connect(port,"127.0.0.1");
}
}
代码分析:
从connect方法讲起,首选客户端处理I/O读写的NioEventLoopGroup线程组,然后继续创建客户端辅助启动类BootStrap,随后需要对其进行配置。与服务端不同,它的Channel需要设置为NioSocketChannel,然后为其添加Handler。此处为了简单直接创建匿名内部类,实现initChannel方法,其作用是当创建NioSocketChannel成功后,在进行初始化时,将它的ChannelHandler设置到ChannelPipeline中,用于处理网络I/O事件。
客户端启动辅助类设置完成后,调用connect方法发起异步连接,然后调用同步方法等待连接成功。
最后,当客户端连接关闭后,客户端主函数退出,退出前释放NIO线程组资源。
TimeClientHandlerNetty.java
public class TimeClientHandlerNetty extends ChannelOutboundHandlerAdapter {
private ByteBuf firstMessage = null;
public TimeClientHandlerNetty() {
byte[] req = "query".getBytes();
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
}
public void channelActive(ChannelHandlerContext ctx){
ctx.writeAndFlush(firstMessage);
}
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");
System.out.println("现在时间是:"+body);
}
public void close(ChannelHandlerContext ctx) {
ctx.close();
}
}