package com.braun.pumpd.netty;
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;
public class NettyServer {
public static final int PORT = 5000;
private Channel serverChannel;
public void start() 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, 100)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
}
});
ChannelFuture f = b.bind(PORT).sync();
// 保存 serverChannel, 之后调用 close, closeFuture sync 的阻塞就会解除了
serverChannel = f.channel();
System.out.println("server started at port " + PORT);
// 这里 sync 会一直阻塞
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
System.out.println("server closed");
}
public void stop() {
if (serverChannel != null) {
serverChannel.close();
serverChannel = null;
}
}
}
网友评论