游戏技术公众号,扫描加入讨论游戏技术
本文来自游戏技术网:http://www.youxijishu.com/view/8
先上一段源代码配置,本代码采用的版本是netty5.0.0;这里主要是游戏服务器开发中netty启动时的基本配置,距离实际应用尚待测试,这里用的一些类我们在下一节进行详细解释,有如有问题可以加底部的QQ群或注册账号在本网页下提问,欢迎交流纠错,代码会进一步完善。
public class ServerManager {
private EventLoopGroup bossGroup = null; // (1)
private EventLoopGroup workerGroup = null;
//
private static EventExecutorGroup HANDER_GROUP = null;
public void startServer() {
ServerCofig serverConfig = ConfigManager.getInstance().getServerConfig();
HANDER_GROUP = new DefaultEventExecutorGroup(serverConfig.getHandlerGroup());
bossGroup = new NioEventLoopGroup(serverConfig.getBossGroup()); // (1)
workerGroup = new NioEventLoopGroup(serverConfig.getWorkGroup());
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("decode",new MessageDecodeHandler(1024 * 1024, 4, 4));
ch.pipeline().addLast("encode",new MessageEncodeHandler());
ch.pipeline().addLast(HANDER_GROUP,"logic",new ServerLogicHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(serverConfig.getPort()).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to
// gracefully
// shut down your server.
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public void stop() {
int quietPeriod = 5;
int timeout = 30;
TimeUnit timeUnit = TimeUnit.SECONDS;
workerGroup.shutdownGracefully(quietPeriod, timeout, timeUnit);
bossGroup.shutdownGracefully(quietPeriod, timeout, timeUnit);
HANDER_GROUP.shutdownGracefully(quietPeriod, timeout, timeUnit);
}
}