<code
class
=
"java"
>
public
class
TimeServer {
private
int
count
= 0;
public
void bind(int port) {
try
{
EventLoopGroup bossGroup =
new
NioEventLoopGroup();
EventLoopGroup workGroup =
new
NioEventLoopGroup();
ServerBootstrap b =
new
ServerBootstrap();
b.group(bossGroup, workGroup).channel(NioServerSocketChannel.
class
)
.childHandler(
new
ChannelInitializer<SocketChannel>() {
@Override
protected
void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(
new
LineBasedFrameDecoder(1024));
arg0.pipeline().addLast(
new
StringDecoder());
arg0.pipeline().addLast(
new
ChannelInboundHandlerAdapter() {
@Override
public
void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(
"The Time Server Received order:"
+ msg +
"; the counter is:"
+ ++
count
);
}
});
}
});
ChannelFuture future = b.bind(port).sync();
System.out.println(
"Server start listen at "
+ port);
future.channel().closeFuture().sync();
System.out.println(
"执行到这里 "
+ port);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
public
static
void main(String[] args) {
new
TimeServer().bind(10000);
}
}</code>