moon game server的一个使用示例,搭建简单的房间类游戏服务器框架
多人简易版球球大作战,游戏服务器框架moon的一个使用示例。 主要演示
One Player One Service模式,处理玩家非共享状态,提高单服承载能力和更加Clean的内存管理Redis连接池服务的使用sharetable管理和更新游戏配表lua-language-server插件,即可获得代码提示能力,如果没有代码提示,在.vscode目录下, 创建或者修改settings.json, 添加 {
"Lua.workspace.library": [
"./moon/lualib/",
"./moon/service/"
]
}Hub Server:
Game Server开启了7种服务:
目录结构
…git clone --recursive https://github.com/sniper00/MoonDemo.git安装redis采用默认配置即可。如需要修改数据库配置, 可以修改server目录下的serverconf.lua。
如果想使用postgresql, 修改server目录下的serverconf.lua中pgsql相关配置,main_game.lua 中取消db_game服务的注释,这样userdata数据会保存到postgresql中
windows使用 start_server.bat 脚本运行。linux和macos使用start_hub.sh,start_game.sh依次启动。默认会自动运行机器人服务。配表 可以修改机器人数量
简易后台管理
telnet 127.0.0.1 8003, 输入 S1 help如需要自己部署,可以修改node.json中的ip地址
Client请使用unity2022 启动执行第一个场景Prepare。
vscoderequire("common.LuaPanda").start("127.0.0.1", 8818)F5启动vscode-LuaPanda调试器
使用vscode,在该服务的逻辑代码出下断点
运行服务器,触发断点处的逻辑
客户端主要用来演示怎样使用 asyn/await 来处理网络消息,等异步操作。
var v = await Network.Call(UserData.GameSeverID, new C2SLogin { openid = userName.text });
if (v.ok)
{
UserData.time = v.time;
UserData.username = userName.text;
await Network.Call(UserData.GameSeverID, new C2SMatch {});
SceneManager.LoadScene("MatchWait");
}
else
{
MessageBox.Show("auth failed");
}
//获取请求结果或者逻辑ErrorCode
var callResult = await Network.Call(UserData.GameSeverID, new NetMessage.C2SHello
{
Hello = "world"
});
if (!callResult.IsFirstResponse)
{
Debug.Log("error:" + callResult.Response2.Code);
}//注册回调方式的网络消息
Network.Register((res) =>
{
MessageBox.SetVisible(false);
SceneManager.LoadScene("Game");
});需要安装python3
修改server的protocol目录下的proto文件,协议命名规则
C2Sxxxx表示客户端发送给服务器的消息;S2Cxxxxx,SBCxxxxx 表示服务器发送给客户端的消息,其中SBC表示广播消息,只是为了便于区分。user.proto
center.proto
room.proto
common.proto
annotations.proto 只生成lua注解时使用
编写完成协议后,运行tools目录下的moonfly.bat,其它平台运行python3 moonfly.py
protocol目录的文件都会生成lua注解,建议逻辑中多定义proto结构,提高开发速度,特别是复杂的对象,能达到 typescript 80% 的代码提示能力。对于关键数据可以用使用 verify_proto 进行验证,如需要存数据库的数据。
如果是小游戏之类的客户端,不想采用
protobuf作为通信协议,可以通过修改这里, 采用json作为通信协议。注意Demo自带的Unity客户端暂时不支持切换Json协议。
在 protocol/user.proto 中添加, 然后运行tools/moonfly.bat
//客户端发送
message C2SHello
{
string hello = 1;
}
//服务器返回
message S2CWorld
{
string world = 1;
}在game/user/目录下新建文件 "Hello.lua"
local common = require "common"
local GameCfg = common.GameCfg --游戏配置
local ErrorCode = common.ErrorCode --逻辑错误码
local CmdCode = common.CmdCode --客户端通信消息码
---@type user_context
local context = ...
local scripts = context.scripts ---方便访问同服务的其它lua模块
local Hello = {}
---这里初始化本模块相关的数据
function Hello.Init()
-- local DB = scripts.UserModel.Get()
-- if not DB.hello then
-- DB.hello = {
-- a = 1,
-- b = 2
-- }
-- end
end
---这里可以访问其它模块,做更多初始化工作
function Hello.Start()
--scripts.Item.AddItem(1,1,1)
end
return Hello…No open issues yet, or sync has not completed.