|
通过netty框架实现一个简单的服务端和客户端框架,相比于前面所说的NIO,netty的api使用更加简单灵活,扩展性强。
package com.xpn.netty.netty
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 InterruptedException {
// 配置NIO线程组
EventLoopGroup bossGroup = new NioEventLoopGroup()
EventLoopGroup workerGroup = new NioEventLoopGroup()
try {
ServerBootstrap bootstrap = new ServerBootstrap()
bootstrap.group(bossGroup, workerGroup)
bootstrap.channel(NioServerSocketChannel.class)
bootstrap.option(ChannelOption.SO_BACKLOG, 1024)
bootstrap.childHandler(new ChildChannelHandler())
// 绑定端口,同步等待成功
ChannelFuture future = bootstrap.bind(port).sync()
// 等待服务端监听端口关闭,等待服务端链路关闭之后main函数才退出
future.channel().closeFuture().sync()
} finally {
// 优雅退出,释放线程池资源
bossGroup.shutdownGracefully()
workerGroup.shutdownGracefully()
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler())
}
}
public static void main(String[] args) throws InterruptedException {
int port = 8080
if (args != null && args.length > 0) {
port = Integer.parseInt(args[0])
}
new TimeServer().bind(port)
}
}
package com.xpn.netty.netty
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
public class TimeClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
String host = "localhost"
int port = 8080
EventLoopGroup workerGroup = new NioEventLoopGroup()
try {
Bootstrap bootstrap = new Bootstrap()
bootstrap.group(workerGroup)
bootstrap.channel(NioSocketChannel.class)
bootstrap.option(ChannelOption.SO_KEEPALIVE, true)
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler())
}
})
// 发起异步连接操作
ChannelFuture future = bootstrap.connect(host, port).sync()
future.channel().closeFuture().sync()
} catch (Exception e) {
workerGroup.shutdownGracefully()
}
}
}
package com.xpn.netty.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.Date;
public class TimeServerHandler extends ChannelHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
@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("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);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
}
package com.xpn.netty.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.logging.Logger;
public class TimeClientHandler extends ChannelHandlerAdapter {
private static final Logger LOGGER = Logger
.getLogger(TimeClientHandler.class.getName());
private final ByteBuf firstMessage;
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 exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
LOGGER.warning("Unexpected exception from downstrema : "
+ cause.getMessage());
ctx.close();
}
@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);
}
}
|