前言
上一篇博文中主要介绍了三种IO模式,Netty是一个高性能、异步事件驱动的Java NIO框架,本文以一个简单的Netty程序带领大家先来领略一下Netty的风采,程序的功能主要是获取当前的服务器时间。
客户端
TimeClient.java
public class TimeClient {
public void connect(int port, String host) throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try {
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 = 8800;
new TimeClient().connect(port, "localhost");
}
}
TimeClientHandler.java
public class TimeClientHandler extends ChannelHandlerAdapter {
private final ByteBuf firstMessage;
public TimeClientHandler(){
byte[] req = "QUERY TIME ORDER".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[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("Now is : " + body);
}
public void exceptionCaught(ChannelHandlerContext ctx) throws Exception{
ctx.close();
}
}
服务端
TimeServer.java
public class TimeServer {
public void bind(int port) throws Exception{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChannelInitializer<SocketChannel>(){
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception{
int port = 8800;
new TimeServer().bind(port);
}
}
TimeServerHandler.java
public class TimeServerHandler extends ChannelHandlerAdapter {
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("The time server receive 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);
}
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{
ctx.flush();
}
public void exceptionCaught(ChannelHandlerContext ctx) throws Exception{
ctx.close();
}
}
运行结果
客户端
服务端
总结
“蚊子虽小,五脏俱全”。上述代码功能虽然简单,但是却涵盖了例如Channel、ChannelPipeline、EventLoopGroup、EventLoopGroup等Netty最核心的组件,这些核心组件会在后续的博文中详细讲述。