Netty完成时间请求服务
- Netty时间服务器服务端 TimeServer
package com.helloworld.hellonetty.server;
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;
public class TimeServer{
public void bind(int port) throws Exception{
/**
* ①配置服务端的NIO 线程组
* EventLoopGroup 是NIO 线程组,专门用于处理网络事件,本质是Reactor 线程组。
*/
EventLoopGroup bossGroup = new NioEventLoopGroup(); //用于服务端接受客户端的连接
EventLoopGroup workerGroup = new NioEventLoopGroup(); //用于进行SocketChannel 的网络读写
try{
/**
* ServerBootstrap 用于启动NIO服务端的辅助启动类
* 目的是降低服务端的开发复杂度
*/
ServerBootstrap b = new ServerBootstrap();
//②配置服务端服务启动类
b.group(bossGroup, workerGroup)
/**
* 设置创建的 Channel为 NioServerSocketChannel
* 它的功能对应于 JDK NIO类库中的 SeverSocketChannel类
*/
.channel(NioServerSocketChannel.class)
//配置 NioServerSocketChannel的 TCP参数 此处将它的 backlog设置为1024
.option(ChannelOption.SO_BACKLOG, 1024) //配置TCP参数
/**
* 绑定 I/O事件的处理类 ChildChannelHandler
* 主要用于处理网络I/O事件 如记录日志,对消息进行编解码等
* 它的作用类似于 Reactor模式中的 Handler类
*/
//方法一
.childHandler(new ChildChannelHandler());
//方法二
// .childHandler(new ChannelInitializer<SocketChannel>() {
//
// @Override
// protected void initChannel(SocketChannel arg0) throws Exception {
// arg0.pipeline().addLast(new TimeServerHandler());
//
// }
// });
//
//
/**
* ③绑定端口,同步等待成功
* 调用它的bind方法绑定监听端口
* 调用它的同步阻塞方法 sync等待绑定操作完成
*
* ChannelFuture 功能类似于 JDK的 java.util.concurrent.Future,主要用于异步操作的通知回调
*/
ChannelFuture f = b.bind(port).sync(); //异步地绑定服务器,调用sync()方法阻塞等待直到绑定完成。
//④等待服务端监听端口关闭 等待服务端链路关闭之后main函数才退出
f.channel().closeFuture().sync(); //获取ChannelFuture,并且阻塞当前线程直到它完成。
} finally {
/**
* ⑤优雅退出,释放线程池资源
*
* 调用 NIO线程组的 shutdownGracefully进行优雅退出
* 它会释放跟 shutdownGracefully相关联的资源
*/
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
//I/O 事件处理类
private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new TimeServerHandler());
}
}
/**
*
* @param args
* @throws Exception
*/
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);
}
}
- Netty时间服务器服务端 TimeServerhandler
package com.helloworld.hellonetty.server;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
*
* TimeServerHandler继承自 ChannelInboundHandlerAdapter 用于对网络事件的读写操作
* 通常只需关注 channelRead和 exceptionCaught方法
*
* 说明:当服务器接受到消息后,channelRead方法会被调用,具体消息为msg,用户可以对该消息进行处理,
* channelReadComplete将之前写入客户端的消息刷新,待操作完成后关闭。
* exceptionCaught方法则会捕捉处理中的异常。
*/
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//ByteBuf 类似于 java.nio.ByteBuffer 对象
ByteBuf buf = (ByteBuf) msg;
//通过 ByteBuf的 readableBytes方法可以获取缓冲区可读的字节数,根据可读的字节数创建 byte数组
byte[] req = new byte[buf.readableBytes()];
//通过 ByteBuf的 readBytes方法将缓冲区中的字节数组复制到新建的 byte数组中
buf.readBytes(req);
//通过 new String构造函数获取请求消息
String body = new String(req, "UTF-8");
System.out.println("This 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());
//ctx.writeAndFlush(resp);
//通过 ChannelHandlerContext的 write方法异步发送应答消息给客户端
ctx.write(resp);
}
/**
* 通知ChannelInboundHandlerAdapter 最后一次对channelRead()的调用是当前批量读取中的最后一条消息。
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
/**
* ctx.write(resp) 是将信息写到消息队列,而不是每次write就写入SocketChannel
* ctx.flush() 是将消息发送队列中的信息写到SocketChannel中发送给对方,
* ctx.writeAndFlush(resp) 直接写入SocketChannel
*
* 从性能角度讲,为了防止频繁地唤醒 Selector进行消息发送,Netty的 write方法并不直接将消息写入 SocketChannel中,
* 调用 write方法只是把待发送的消息放到发送缓冲数组中,再通过 flush方法,将发送缓冲区中的消息全部写入 SocketChannel中
*/
ctx.flush();
}
/**
* 处理过程中出现的异常
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//当发生异常时,关闭ChannelHandlerContext,释放和ChannelHandlerContext相关联的句柄等资源
ctx.close();
}
}
- Netty 时间服务器客户端 TimeClient
package com.helloworld.hellonetty.client;
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;
/**
* 客户端部分的逻辑同服务器类似,也包含引导客户端和实现客户端处理器两部分,客户端连接服务端,并且接收服务端的消息,关闭连接等。
*
* 说明:其引导部分与服务端非常类似,流程非常类似,其给出了服务端的地址和端口号,Bootstrap的connect函数将会根据指定的地址和端口号连接服务器。
*/
public class TimeClient {
public void connect(int port, String host) throws Exception{
//配置客户端NIO线程组 创建客户端处理I/O读写的 NioEventLoopGroup线程组
EventLoopGroup group = new NioEventLoopGroup();
/**
* 创建客户端辅助启动类 Bootstrap,并对其进行配置
*
* 与服务端不同的是,它的 Channel需要设置为 NioSocketChannel,并为其添加 Handler
*/
try{
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class) //不同处***
.option(ChannelOption.TCP_NODELAY, true)
/**
* 此处为了简单直接创建匿名类部类,实现 initChannel方法
* 作用:当创建 NioSocketChannel成功之后,在进行初始化时,将它的 ChannelHandler设置到ChannelPipeline中,
* 用于处理网络I/O事件
*/
.handler(new ChannelInitializer<SocketChannel>() { //不同处***
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new com.helloworld.hellonetty.client.TimeClientHandler());
}
});
//发起异步连接操作,调用同步方法等待连接成功
ChannelFuture f = b.connect(host, port).sync();
//等待客户端链路关闭
f.channel().closeFuture().sync();
}finally{
//优雅退出,释放NIO线程组
group.shutdownGracefully();
}
}
/**
*
* @param args
* @throws Exception
*/
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");
}
}
- Netty时间服务器客户端 TimeClientHandler
package com.helloworld.hellonetty.client;
import java.util.logging.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* 本部分完成用户实际的业务逻辑,需要重写如下三个函数
* · channelActive函数,在建立了与服务端的连接后该函数被调用。
* · channelRead函数,当接收到服务端发送来的消息后被调用。
* · exceptionCaught函数,当处理发生异常时被调用。
*
* 说明:当同服务器的连接建立后,客户端会发送消息至服务端,然后当接收到服务端发送来的消息时,打印该消息。
*/
public class TimeClientHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
private final ByteBuf firstMessage;
/**
* Creates a client-side handler.
*/
public TimeClientHandler() {
byte[] req = "QUERY TIME ORDER".getBytes();
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
}
//在到服务器的连接已经建立之后将被调用
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(firstMessage);
}
//当从服务器接受到一条消息时被调用
@Override
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);
}
//处理过程中出现的异常
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//释放资源
logger.warning("Unexpected exception from downstream :" + cause.getMessage());
ctx.close();
}
}
运行结果:
所需 jar 包下载:https://download.csdn.net/download/ib_yeang/10625922
参考自《Netty 权威指南》