T2FGame.Samples.GameServer 1.0.9

dotnet add package T2FGame.Samples.GameServer --version 1.0.9
                    
NuGet\Install-Package T2FGame.Samples.GameServer -Version 1.0.9
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="T2FGame.Samples.GameServer" Version="1.0.9" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="T2FGame.Samples.GameServer" Version="1.0.9" />
                    
Directory.Packages.props
<PackageReference Include="T2FGame.Samples.GameServer" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add T2FGame.Samples.GameServer --version 1.0.9
                    
#r "nuget: T2FGame.Samples.GameServer, 1.0.9"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package T2FGame.Samples.GameServer@1.0.9
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=T2FGame.Samples.GameServer&version=1.0.9
                    
Install as a Cake Addin
#tool nuget:?package=T2FGame.Samples.GameServer&version=1.0.9
                    
Install as a Cake Tool

T2FGame.Samples.GameServer

这是一个完整的 T2FGame 游戏服务器示例,演示框架的核心功能。

功能演示

1. Action 控制器

[ActionController(cmd: CmdModule.User)]  // 模块命令
public class UserController
{
    [ActionMethod(subCmd: UserCmd.Login)]  // 子命令
    public Task<LoginResponse> Login(LoginRequest request, FlowContext context)
    {
        // 业务逻辑
    }
}

2. 参数验证 (DataAnnotations)

public class RegisterRequest : IMessage<RegisterRequest>
{
    [Required(ErrorMessage = "邮箱不能为空")]
    [EmailAddress(ErrorMessage = "不是一个合法的电子邮件地址")]
    public string Email { get; set; } = "";

    [Range(1, 120, ErrorMessage = "年龄必须在1-120之间")]
    public int Age { get; set; }
}

验证失败时会自动返回错误,并在控制台输出:

┏━━━━━ Error. [(UserController.cs).Register] ━━━━━ [1-2] ━━━━━
┣ userId: (未登录)
┣ sessionId: abc123
┣ 连接方式: WebSocket
┣ 参数: RegisterRequest: { "email": "invalid", "age": 10 }
┣ 错误码: 202
┣ 错误信息: 不是一个合法的电子邮件地址
┣ 时间: 0 ms (业务方法总耗时)
┗━━━━━ [T2FGame] ━━━━━ [线程:Worker-1] ━━━━━━━ [traceId:abc123def456] ━━━━━

3. 认证控制

// 需要登录才能访问(默认 requireAuth = true)
[ActionMethod(subCmd: UserCmd.GetInfo)]
public Task<UserInfo> GetUserInfo(FlowContext context)
{
    // context.UserId 已经是登录用户的 ID
}

// 无需登录即可访问
[ActionMethod(subCmd: UserCmd.Login, requireAuth: false)]
public Task<LoginResponse> Login(LoginRequest request, FlowContext context)
{
    // 登录成功后设置认证状态
    UserIdSettingKit.SettingUserId(context, userId);
}

4. 响应缓存

[ActionMethod(subCmd: UserCmd.UpdateInfo)]
[ActionCache(60, Scope = CacheScope.User)]  // 缓存 60 秒,用户级别
public Task<UserInfo> GetUserInfoCached(FlowContext context)
{
    // 第一次调用会执行,后续 60 秒内直接返回缓存
}

5. 限流控制

[ActionMethod(subCmd: ChatCmd.Send)]
[RateLimit(10, 60)]  // 每分钟最多发送 10 条消息
public async Task<ChatNotify> SendMessage(ChatMessage request, FlowContext context)
{
    // 超过限制会返回 RateLimited 错误
}

6. 消息广播

// 广播给所有人
await _broadcaster.BroadcastAllAsync(cmdMerge, notify);

// 发送给指定用户
await _broadcaster.PushToUserAsync(targetUserId, cmdMerge, notify);

// 广播给用户列表
await _broadcaster.BroadcastToUsersAsync(userIds, cmdMerge, notify);

7. 模块间调用

[ActionController(cmd: CmdModule.Battle)]
public class BattleController
{
    [ActionMethod(subCmd: 1, timeoutMs: 5000)]  // 5 秒超时
    public async Task<BattleStartResponse> StartBattle(BattleStartRequest request, FlowContext context)
    {
        // 调用用户模块获取玩家信息
        var cmdInfo = new CmdInfo(CmdKit.GetMergeCmd(CmdModule.User, UserCmd.GetInfo));
        var userInfo = await context.ModuleInvoker!.InvokeAsync<UserInfo>(cmdInfo, context);

        // 使用用户信息创建战斗...
    }
}

8. 忽略调试输出

[ActionMethod(subCmd: 99, requireAuth: false)]
[IgnoreDebugInOut]  // 心跳等高频操作可以忽略,不在控制台输出
public Task Heartbeat(FlowContext context)
{
    return Task.CompletedTask;
}

运行示例

cd samples/T2FGame.Samples.GameServer
dotnet run

配置说明

服务注册

// 1. 注册 Action 框架
services.AddT2FGameAction(typeof(Program).Assembly);

// 2. 注册 Pipeline 处理链
services.AddActionPipeline(options =>
{
    options.UseTraceHandler = true;           // 链路追踪
    options.UseAuthenticationHandler = true;  // 认证检查
    options.UseValidationHandler = true;      // 参数验证
    options.UseCacheHandler = true;           // 响应缓存
    options.UseRateLimitHandler = true;       // 限流控制
    options.UseDebugInOutHandler = true;      // 调试输出
    options.UseLoggingHandler = true;         // 日志记录
});

// 3. 注册消息推送服务
services.AddBroadcaster();

// 4. 注册 Socket 网络层
services.AddT2FGameSocket();

调试输出配置

services.Configure<DebugInOutOptions>(options =>
{
    options.Enabled = true;
    options.MinTriggerTimeMs = 0;       // 0=打印所有,>0=只打印慢请求
    options.PrintRequestData = true;    // 打印请求参数
    options.PrintResponseData = true;   // 打印响应数据
    options.MaxDataLength = 200;        // 最大数据长度
});

项目结构

T2FGame.Samples.GameServer/
├── Controllers/
│   ├── UserController.cs      # 用户模块:登录、注册、信息查询
│   ├── ChatController.cs      # 聊天模块:消息发送、广播
│   └── BattleController.cs    # 战斗模块:模块间调用示例
├── Protos/
│   └── Messages.cs            # 消息定义(请求/响应)
├── Program.cs                 # 程序入口
└── README.md                  # 本文件

错误码说明

错误码 说明
0 成功
2 内部错误
100 未授权
202 验证失败
300 资源不存在
301 资源已存在
500 请求限流
501 请求超时
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.9 405 12/11/2025
1.0.8 403 12/11/2025
1.0.7 397 12/11/2025
1.0.6 403 12/11/2025
1.0.5 418 12/10/2025
1.0.4 417 12/10/2025
1.0.3 422 12/9/2025
1.0.2 331 12/8/2025
0.0.1 329 12/8/2025