NoticLuaSample - ScutGame/Scut GitHub Wiki

此章节介绍公告示例 - Lua脚本

公告示例是介绍服务端如何发送多条数据给客户,需要怎么定义一个列表结构的协议接口;客户端使用协议平台工具模拟请求发送。

服务端开发流程

  <connectionStrings>
    <add name="GameData" providerName="SqlDataProvider" connectionString="Data Source=localhost;Database=GameData;Uid=sa;Pwd=123;" />
  </connectionStrings>

  • 定义公告Entity模型,配置为Share类型(它需要读取时全部加载,不能以玩家上线后部分加载);
using System;
using ProtoBuf;
using ZyGames.Framework.Model;

namespace GameNotice.Model
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable, ProtoContract]
    [EntityTable(CacheType.Entity, "GameData")]
    public class Notice :  ShareEntity
    {

        /// <summary>
        /// </summary>
        public Notice()
            : base(false)
        {
        }        
        /// <summary>
        /// </summary>
        public Notice(int id)
            : this()
        {
            Id = id;
        }
    
        [ProtoMember(1)]
        [EntityField(true)]
        public int Id { get; private set; }
     
        [ProtoMember(2)]
        [EntityField]
        public string Title { get; set; }

        /// <summary>
        /// 
        /// </summary>        
        [ProtoMember(3)]
        [EntityField]
        public string Content { get; set; }

        /// <summary>
        /// 
        /// </summary>        
        [ProtoMember(4)]
        [EntityField]
        public DateTime CreateDate { get; set; }
    
    }
}

  • 创建Python脚本的Action2001协议,输出列表类型的协议结构:
#!lua

function Action2001:buildPacket(writer, urlParam, actionResult)
    PushIntoStack(writer, actionResult.PageCount)
    PushIntoStack(writer, actionResult.ItemCount)
    local len = actionResult.ItemCount
    for i=1,len,1 do
	local info = actionResult.dsItemCollect[i-1]
        dsItem = CreateDataStruct()
        PushIntoStack(dsItem, info.Title)
        PushIntoStack(dsItem, info.Content)
        PushIntoStack(dsItem, FormatDateString(info.CreateDate, "yyyy-MM-dd HH:mm:ss"))
        PushIntoStack(writer, dsItem)
	end
    return true
end

  • 在游戏服启动时,初始一些公告信息(正式游戏会由后台增加),打开MainClass类修改
public class MainClass : GameSocketHost
{

    protected override void OnStartAffer()
    {
        InitNotice();
    }

    private void InitNotice()
    {
        var cacheSet = new ShareCacheStruct<Notice>();
        for (int i = 0; i < 5; i++)
        {
	    int id = (int)cacheSet.GetNextNo(); //取Redis中的自增编号
	    Notice notice = new Notice(id);
	    notice.Title = "tile" + id;
	    notice.Content = "Content" + id;
	    notice.CreateDate = DateTime.Now;
	    cacheSet.Add(notice);
        }
    }

}

  • 启动服务器运行,需要调试开启Config中的调试模式,启动失败可以在Nlog文件中查看详细错误信息
#! GameServer.exe.config

    <add key="Script_IsDebug" value="True"/> <!--开启脚本调试模式-->
    <add key="Lua_Disable" value="False" />
  • 打开协议平台工具,在"协议调试"项,模拟客户端请求发送(Host:127.0.0.1:9001),成功后会返回结果列表
⚠️ **GitHub.com Fallback** ⚠️