package
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
public class NettyServer extends AbstractIoService {
private int port = 8800;
private static final InternalLogger LOG = InternalLoggerFactory.getInstance(NettyServer.class);
private EventLoopGroup bossGroup = new NioEventLoopGroup(2, new DefaultThreadFactory("server1", true));
private EventLoopGroup workerGroup = new NioEventLoopGroup(4, new DefaultThreadFactory("server2", true));
public NettyServer(String name, int port, AbstractChannelInitializer channelInitializer, AbstractChannelHandlerAdapter channelHandler) {
super(name, channelInitializer, channelHandler);
this.port = port;
}
@Override
public void start() {
try {
ServerBootstrap bootStrap = new ServerBootstrap();
// the parent (acceptor) and the child (client)
bootStrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(channelInitializer);
ChannelFuture channelFuture = bootStrap.bind(port).sync();
if (channelFuture.isSuccess()) {
LOG.info("listen port {} success", port);
}
channelFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
// TODO Auto-generated method stub
LOG.info("##启动完成,刷新客户端存活状态。++++++++++");
if (future.isSuccess()) {
LOG.info("##启动完成,刷新客户端存活状态。");
} else {
LOG.error("#E#客户端启动失败。");
future.cause().printStackTrace();
LOG.error(future.cause().getMessage());
}
}
});
channelFuture.channel().closeFuture().sync();
// f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
@Override
public void close() {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}