从零开始手写mmo游戏从框架到爆炸(二)— 核心组件抽离与工厂模式创建

本文主要是介绍从零开始手写mmo游戏从框架到爆炸(二)— 核心组件抽离与工厂模式创建,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

        上一章我们已经完成了一个基本netty的通信,但是netty的启动很多代码都是重复的,所以我们使用工厂模式来生成不同的ServerBootstrap。

首先创建一个新的组件core组件,和common组件,主要用于netty通信和工具类,从server中分离出来没有本质的区别,就是希望可以把功能分散在不同的组件中,后续方便多人进行协同开发(如果有多人的话)。

eternity-server的pom文件中增加依赖:

    <dependencies><dependency><groupId>com.loveprogrammer</groupId><artifactId>eternity-core</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>

eternity-core的pom文件中增加依赖:

    <dependencies><dependency><groupId>com.loveprogrammer</groupId><artifactId>eternity-common</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>

公共变量

ConstantValue.java common:src/../constants

package com.loveprogrammer.constants;/*** @ClassName ConstantValue* @Description 静态数据类* @Author admin* @Date 2024/1/30 10:01* @Version 1.0*/
public class ConstantValue {public static final String CHANNEL_TYPE_NIO = "NIO";public static final String CHANNEL_TYPE_OIO = "OIO";public static final String PROTOCOL_TYPE_HTTP = "HTTP";public static final String PROTOCOL_TYPE_HTTPS = "HTTPS";public static final String PROTOCOL_TYPE_TCP = "TCP";public static final String PROTOCOL_TYPE_PROTOBUF = "PROTOBUF";public static final String PROTOCOL_TYPE_WEBSOCKET = "WEBSOCKET";public static final String MESSAGE_TYPE_STRING = "STRING";public static final String MESSAGE_TYPE_BYTE = "BYTE";public static final String PROJECT_CHARSET = "UTF-8";public static final int MESSAGE_CODEC_MAX_FRAME_LENGTH = 1024 * 1024;public static final int MESSAGE_CODEC_LENGTH_FIELD_LENGTH = 4;public static final int MESSAGE_CODEC_LENGTH_FIELD_OFFSET = 2;public static final int MESSAGE_CODEC_LENGTH_ADJUSTMENT = 0;public static final int MESSAGE_CODEC_INITIAL_BYTES_TO_STRIP = 0;/*** 登录和下线队列*/public static final int QUEUE_LOGIN_LOGOUT = 1;/*** 业务队列*/public static final int QUEUE_LOGIC = 2;private ConstantValue() {}}

ServerException.java common:src/../exception

public class ServerException extends Exception{private String errMsg;public ServerException(String errMsg) {super(errMsg);this.errMsg = errMsg;}public ServerException(Throwable cause) {super(cause);}
}

 下面是core中的新增代码

ServerConfig.java

/*** @ClassName ServerConfig* @Description 服务基本配置类* @Author admin* @Date 2024/2/4 15:12* @Version 1.0*/
public class ServerConfig {private static final Logger logger = LoggerFactory.getLogger(ServerConfig.class);private Integer port;private String channelType;private String protocolType;private static ServerConfig instance = null;private ServerConfig() {}public static ServerConfig getInstance() {if (instance == null) {instance = new ServerConfig();instance.init();instance.printServerInfo();}return instance;}private void init() {port = 8088;channelType = "NIO";protocolType = "TCP";}public void printServerInfo() {logger.info("**************Server INFO******************");logger.info("protocolType  : " + protocolType);logger.info("port          : " + port);logger.info("channelType   : " + channelType);logger.info("**************Server INFO******************");}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}public String getChannelType() {return channelType;}public void setChannelType(String channelType) {this.channelType = channelType;}public String getProtocolType() {return protocolType;}public void setProtocolType(String protocolType) {this.protocolType = protocolType;}
}

ServerBootstrapFactory.java

package com.loveprogrammer.base.factory;import com.loveprogrammer.base.bean.ServerConfig;
import com.loveprogrammer.constants.ConstantValue;
import com.loveprogrammer.exception.ServerException;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;/*** @ClassName ServerBootstrapFactory* @Description Bootstrap工厂类* @Author admin* @Date 2024/2/4 15:13* @Version 1.0*/
public class ServerBootstrapFactory {private ServerBootstrapFactory() {}public static ServerBootstrap createServerBootstrap() throws ServerException {ServerBootstrap serverBootstrap = new ServerBootstrap();switch (ServerConfig.getInstance().getChannelType()) {case ConstantValue.CHANNEL_TYPE_NIO:EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();serverBootstrap.group(bossGroup, workerGroup);serverBootstrap.channel(NioServerSocketChannel.class);return serverBootstrap;case ConstantValue.CHANNEL_TYPE_OIO:serverBootstrap.group(new OioEventLoopGroup());serverBootstrap.channel(OioServerSocketChannel.class);return serverBootstrap;default:throw new ServerException("Failed to create ServerBootstrap,  " +ServerConfig.getInstance().getChannelType() + " not supported!");}}
}

ServerChannelFactory.java

package com.loveprogrammer.base.factory;import com.loveprogrammer.base.bean.ServerConfig;
import com.loveprogrammer.base.network.channel.tcp.str.TcpServerStringInitializer;
import com.loveprogrammer.constants.ConstantValue;
import com.loveprogrammer.exception.ServerException;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** @ClassName ServerChannelFactory* @Description channel工厂类* @Author admin* @Date 2024/2/4 15:13* @Version 1.0*/
public class ServerChannelFactory {private static final Logger logger = LoggerFactory.getLogger(ServerChannelFactory.class);public static Channel createAcceptorChannel() throws ServerException {Integer port = ServerConfig.getInstance().getPort();final ServerBootstrap serverBootstrap = ServerBootstrapFactory.createServerBootstrap();serverBootstrap.childHandler(getChildHandler());logger.info("创建Server...");try {ChannelFuture channelFuture = serverBootstrap.bind(port).sync();channelFuture.awaitUninterruptibly();if(channelFuture.isSuccess()) {return channelFuture.channel();}else{String errMsg = "Failed to open socket! Cannot bind to port: " + port + "!";logger.error(errMsg);throw new ServerException(errMsg);}} catch (Exception e) {logger.debug(port + "is bind");throw new ServerException(e);}}private static ChannelInitializer<SocketChannel> getChildHandler() throws ServerException {String protocolType = ServerConfig.getInstance().getProtocolType();if (ConstantValue.PROTOCOL_TYPE_HTTP.equals(protocolType) || ConstantValue.PROTOCOL_TYPE_HTTPS.equals(protocolType)) {} else if (ConstantValue.PROTOCOL_TYPE_TCP.equals(protocolType)) {return new TcpServerStringInitializer();} else if (ConstantValue.PROTOCOL_TYPE_WEBSOCKET.equals(protocolType)) {} else if (ConstantValue.PROTOCOL_TYPE_PROTOBUF.equals(protocolType)) {} else {}String errMsg = "undefined protocol:" + protocolType + "!";throw new ServerException(errMsg);}}

TcpMessageStringHandler.java

package com.loveprogrammer.base.network.channel.tcp.str;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** @ClassName TcpMessageStringHandler* @Description tcp消息处理类* @Author admin* @Date 2024/2/4 15:16* @Version 1.0*/
public class TcpMessageStringHandler extends SimpleChannelInboundHandler<String> {private static final Logger logger = LoggerFactory.getLogger(TcpMessageStringHandler.class);@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {logger.debug("异常发生", throwable);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {super.channelRead(ctx, msg);}@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String msg) {logger.info("数据内容:data=" + msg);String result = "我是服务器,我收到了你的信息:" + msg;result += "\r\n";ctx.writeAndFlush(result);}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {logger.info("建立连接");super.channelActive(ctx);}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {logger.info("连接断开");super.channelInactive(ctx);}
}

 TcpServerStringInitializer.java

package com.loveprogrammer.base.network.channel.tcp.str;import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;/*** @ClassName TcpServerStringInitializer* @Description TODO* @Author admin* @Date 2024/2/4 15:15* @Version 1.0*/
public class TcpServerStringInitializer  extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));pipeline.addLast("decoder", new StringDecoder());pipeline.addLast("encoder", new StringEncoder());pipeline.addLast(new TcpMessageStringHandler());}}

  修改启动类EternityServerMain :

package com.loveprogrammer;import com.loveprogrammer.base.factory.ServerBootstrapFactory;
import com.loveprogrammer.base.factory.ServerChannelFactory;
import com.loveprogrammer.exception.ServerException;
import com.loveprogrammer.netty.simple.SocketServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** Hello world!**/
public class EternityServerMain
{// 为了保证使用时,不需要每次都去创建logger 对象,我们声明静态常量public static final Logger LOGGER = LoggerFactory.getLogger(EternityServerMain.class);public static void main( String[] args ){LOGGER.info( "Hello World!" );// 最基本的启动方法
//        try {
//            LOGGER.info("开始启动Socket服务器...");
//            new SocketServer().run();
//        } catch (Exception e) {
//            LOGGER.error( "服务器启动失败",e);
//        }// 工厂模式启动方法try {Channel channel = ServerChannelFactory.createAcceptorChannel();channel.closeFuture().sync();} catch (Exception e) {LOGGER.error( "服务器启动失败",e);}}
}

 全部源码详见:

gitee : eternity-online: 多人在线mmo游戏 - Gitee.com

分支:step-02

上一章:

从零开始手写mmo游戏从框架到爆炸(一)— 开发环境-CSDN博客

下一章:从零开始手写mmo游戏从框架到爆炸(三)— 服务启动接口与网络事件监听器-CSDN博客

参考:

java游戏服务器开发: https://blog.csdn.net/cmqwan/category_7690685.html

这篇关于从零开始手写mmo游戏从框架到爆炸(二)— 核心组件抽离与工厂模式创建的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/680112

相关文章

SQL Server身份验证模式步骤和示例代码

《SQLServer身份验证模式步骤和示例代码》SQLServer是一个广泛使用的关系数据库管理系统,通常使用两种身份验证模式:Windows身份验证和SQLServer身份验证,本文将详细介绍身份... 目录身份验证方式的概念更改身份验证方式的步骤方法一:使用SQL Server Management S

SpringBoot基础框架详解

《SpringBoot基础框架详解》SpringBoot开发目的是为了简化Spring应用的创建、运行、调试和部署等,使用SpringBoot可以不用或者只需要很少的Spring配置就可以让企业项目快... 目录SpringBoot基础 – 框架介绍1.SpringBoot介绍1.1 概述1.2 核心功能2

PyQt6中QMainWindow组件的使用详解

《PyQt6中QMainWindow组件的使用详解》QMainWindow是PyQt6中用于构建桌面应用程序的基础组件,本文主要介绍了PyQt6中QMainWindow组件的使用,具有一定的参考价值,... 目录1. QMainWindow 组php件概述2. 使用 QMainWindow3. QMainW

Java Jackson核心注解使用详解

《JavaJackson核心注解使用详解》:本文主要介绍JavaJackson核心注解的使用,​​Jackson核心注解​​用于控制Java对象与JSON之间的序列化、反序列化行为,简化字段映射... 目录前言一、@jsonProperty-指定JSON字段名二、@JsonIgnore-忽略字段三、@Jso

Redis高可用-主从复制、哨兵模式与集群模式详解

《Redis高可用-主从复制、哨兵模式与集群模式详解》:本文主要介绍Redis高可用-主从复制、哨兵模式与集群模式的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录Redis高可用-主从复制、哨兵模式与集群模式概要一、主从复制(Master-Slave Repli

Java 如何创建和使用ExecutorService

《Java如何创建和使用ExecutorService》ExecutorService是Java中用来管理和执行多线程任务的一种高级工具,可以有效地管理线程的生命周期和任务的执行过程,特别是在需要处... 目录一、什么是ExecutorService?二、ExecutorService的核心功能三、如何创建

Spring框架中@Lazy延迟加载原理和使用详解

《Spring框架中@Lazy延迟加载原理和使用详解》:本文主要介绍Spring框架中@Lazy延迟加载原理和使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、@Lazy延迟加载原理1.延迟加载原理1.1 @Lazy三种配置方法1.2 @Component

一文带你搞懂Redis Stream的6种消息处理模式

《一文带你搞懂RedisStream的6种消息处理模式》Redis5.0版本引入的Stream数据类型,为Redis生态带来了强大而灵活的消息队列功能,本文将为大家详细介绍RedisStream的6... 目录1. 简单消费模式(Simple Consumption)基本概念核心命令实现示例使用场景优缺点2

使用Python创建一个功能完整的Windows风格计算器程序

《使用Python创建一个功能完整的Windows风格计算器程序》:本文主要介绍如何使用Python和Tkinter创建一个功能完整的Windows风格计算器程序,包括基本运算、高级科学计算(如三... 目录python实现Windows系统计算器程序(含高级功能)1. 使用Tkinter实现基础计算器2.

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3