public abstract class NettyYmaServer extends SessionAbleYmaServer {
private static final Logger log = LoggerFactory.getLogger(NettyYmaServer.class);
private final YmlServerConfig config;
private Channel serverChannel;
public NettyYmaServer(YmlServerConfig config){
this.config = config;
}
public NettyYmaServer(){
this(new DefaultServerConfig());
}
@Override
public void start(){
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(config.getBoosGroup(),config.getWorkerGroup())
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
.addLast(new ByteArrayEncoder())
.addLast(new ByteArrayDecoder())
.addLast(NettyYmaServer.this);
}
});
ChannelFuture future = bootstrap.bind(config.getSocketAddress());
future.addListener(f -> {
if(f.isDone() && f.isSuccess()){
this.serverChannel = future.channel();
log.info("Start ws server success");
}
if(f.isDone() && f.cause() != null){
log.error("Start ws server fail throw={}", f.cause().getMessage());
future.channel().close();
}
});
}
@Override
public void stop(){
if(serverChannel != null && serverChannel.isOpen()){
final int waitSec = 10;
CountDownLatch latch = new CountDownLatch(1);
serverChannel.close().addListener(f -> {
config.getWorkerGroup().schedule(() -> {
log.info("Shutdown dispatcher success...");
config.getWorkerGroup().shutdownGracefully();
latch.countDown();
}, waitSec - 2, TimeUnit.SECONDS);
log.info("Close ws server socket success={}", f.isSuccess());
config.getBoosGroup().shutdownGracefully();
});
try{
latch.await(waitSec, TimeUnit.SECONDS);
}catch (InterruptedException e){
log.warn("Shutdown ws server interrupted exception={}", e.getMessage());
}
}
}
....