Notifications
Article
Netty在游戏服务器中的应用
Published 10 months ago
128
0
Netty在游戏服务器中的应用
在实际的游戏服务端开发中,我们经常需要千万级别以上的前端访问,这时候,服务器采用Netty这种成熟的架构可以减少在开发中遇到的坑。Netty模块分为以下部分:
1.启动
private static final Log log = Log.getLog(NettyPlugin.class); // 初始最大活跃连接数,根据服务器的实际负载配置这参数 private int maxActive = 102400; private boolean isStarted = false; private int port; private EventLoopGroup boss; private EventLoopGroup worker; public boolean start() { if (isStarted) return true; bind(); isStarted = true; return true; } private void bind() { boss = new NioEventLoopGroup(); worker = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_BACKLOG, maxActive); // 连接数 bootstrap.option(ChannelOption.TCP_NODELAY, true); // 不延迟,消息立即发送 bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // 长连接 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline p = socketChannel.pipeline(); p.addLast(new SocksServerHandler()); } }); ChannelFuture f = bootstrap.bind(port).sync(); if (f.isSuccess()) { log.info("启动Netty服务成功,端口号:" + this.port); } // 关闭连接 f.channel().closeFuture().sync(); } catch (Exception e) { log.info("启动Netty服务异常,异常信息:" + e.getMessage()); e.printStackTrace(); } }
2.netty关闭
public boolean stop() { boss.shutdownGracefully(); worker.shutdownGracefully(); isStarted = false; return true; }
3.SocksServer处理,收到啥回复啥
public final class SocksServerHandler extends SimpleChannelInboundHandler<SocksMessage> { private static final Log log = Log.getLog(SocksServerHandler.class); public static final SocksServerHandler INSTANCE = new SocksServerHandler(); SocksServerHandler() { } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; StringBuffer sb = new StringBuffer(); while (in.isReadable()) { // (1) sb.append((char) in.readByte()); } log.info(sb.toString()); ByteBuf b = ctx.alloc().buffer(); b.writeBytes(sb.toString().getBytes()); ctx.pipeline().write(b); ctx.pipeline().flush(); } @Override public void channelRead0(ChannelHandlerContext ctx, SocksMessage socksRequest) throws Exception { log.info("channelRead0"); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { log.info("channelReadComplete"); ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { log.info("exceptionCaught"); throwable.printStackTrace(); SocksServerUtils.closeOnFlush(ctx.channel()); } }
一个socket连接会建立一个线程来处理,可以充分发挥服务端多线程的处理能力。这样,就可以在SocksServerHandler里面处理你的业务逻辑了,简单吧。。。

Tags:
veteranyu
Software Engineer - Designer
1
Comments