实验
改造NIO实现的TimeServer
代码
- TimeServer
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* 时间协议服务端
* Created by liqiushi on 2017/12/14.
*/
public class TimeServer {
public static void main(String[] args) {
//1、创建两个线程组 一个是接受连接,一个是用来处理连接
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
//2、需要一个辅助类ServerBootstrap
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class) //创建ServerSocketChannel
.option(ChannelOption.SO_BACKLOG,1024)
//.childHandler(new ChildChannelHandler());
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler());
}
});
//3、绑定端口
try {
ChannelFuture f = b.bind(8001).sync();
//4、等待服务端监听端口关闭
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//释放线程池资源
System.out.println("release!");
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
- TimeServerHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import java.util.Date;
/**
* Created by liqiushi on 2017/12/14.
*/
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("connect established!");
super.channelActive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf readBuf = (ByteBuf) msg;
byte[] req = new byte[readBuf.readableBytes()];
readBuf.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());
ChannelFuture f = ctx.writeAndFlush(resp);
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
System.out.println("compeleted!");
assert f == future;
ctx.close();
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}