public class NettyEchoServer {
private final int port;
EchoServerHandler echoServerHandler =new EchoServerHandler();
public NettyEchoServer(int port) {
this.port = port;
}
public void start() throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
//1 服务引导
ServerBootstrap b = new ServerBootstrap();
//2. 指定nio传输,本地套接字地址
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
//3. 在管道中添加处理
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//4 Binds server, waits for server to close, and releases resources
socketChannel.pipeline().addLast(echoServerHandler);
}
});
//5. bind the server and then wait until the bind completes,
// the call to the "sync()" method will cause this to block until the server is bound.
ChannelFuture f = b.bind().sync();
System.out.println(NettyEchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
// 6. 等待通道关闭
f.channel().closeFuture().sync();
} finally {
// 7. 关闭EventLoopGroup和释放资源
group.shutdownGracefully().sync();
}
public static void main(String[] args) throws InterruptedException {
if (args.length != 1) {
System.err.println(
"Usage: " + NettyEchoServer.class.getSimpleName() +
" <port>");
}
int port = Integer.parseInt(args[0]);
new NettyEchoServer(port).start();
}
}
您绑定服务器,然后等待直到绑定完成,对sync()方法的调用将导致此操作阻塞,直到绑定服务器为止。At #7 the application will wait until the servers channel closes (because we call sync() on the channels close future). You can now shutdown the EventLoopGroup and release all resources, including all created threads(#10).