T2FGame 1.0.9
dotnet add package T2FGame --version 1.0.9
NuGet\Install-Package T2FGame -Version 1.0.9
<PackageReference Include="T2FGame" Version="1.0.9" />
<PackageVersion Include="T2FGame" Version="1.0.9" />
<PackageReference Include="T2FGame" />
paket add T2FGame --version 1.0.9
#r "nuget: T2FGame, 1.0.9"
#:package T2FGame@1.0.9
#addin nuget:?package=T2FGame&version=1.0.9
#tool nuget:?package=T2FGame&version=1.0.9
T2FGame
T2FGame 是一个基于 .NET 9 的高性能分布式游戏服务器框架,灵感来源于 Java 游戏框架 ioGame。
特性
- 高性能网络层:基于 SuperSocket 2.x,支持 TCP、UDP、WebSocket 多协议
- 分布式架构:基于 Microsoft Orleans 的 Actor 模型
- DDD 支持:完整的领域驱动设计基础设施
- Pipeline 处理链:可扩展的请求处理管道(认证、限流、缓存、日志、指标)
- 分布式缓存:支持内存缓存和 Redis 分布式缓存
- 分布式限流:支持滑动窗口和令牌桶算法
- 多数据库支持:MongoDB、Redis
- 房间系统:内置游戏房间和匹配功能
- 代码生成:Source Generator 消除运行时反射,AOT 友好
架构概览
┌─────────────────────────────────────────────────────────────────┐
│ 客户端 (Client) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ T2FGame.Network.Socket │
│ (外部网关 Gateway) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ TCP Server │ │ 协议编解码 │ │ 会话管理 │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ T2FGame.Cluster.Orleans │
│ (消息代理 Broker) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ BrokerGrain │ │ 路由分发 │ │ 负载均衡 │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ GameServerGrain │ │ GameServerGrain │ │ GameServerGrain │
│ (用户模块) │ │ (战斗模块) │ │ (房间模块) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────────┐
│ T2FGame.Action │
│ (业务处理 Pipeline) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ 认证/授权 │ │ Action 调用 │ │ 异常处理 │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────────┐
│ T2FGame.Core │
│ (DDD 基础设施) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Entity │ │ Result 模式 │ │ 领域事件 │ │
│ │ AggregateRoot│ │ Error 处理 │ │ EventBus │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ T2FGame.Persistence.MongoDB │
│ (数据持久化) │
└─────────────────────────────────────────────────────────────────┘
模块说明
核心模块
代码生成模块(可选,编译时优化)
| 模块 | 说明 | NuGet |
|---|---|---|
| T2FGame.CodeGen.Action | Action 源生成器,消除运行时反射 | |
| T2FGame.CodeGen.Protocol | 协议源生成器,自动生成 .proto 文件 |
开发工具(独立安装)
| 模块 | 说明 | NuGet |
|---|---|---|
| T2FGame.Tools | 开发工具库,Proto 导出、客户端 SDK 生成 | |
| T2FGame.Tools.Cli | CLI 工具(t2f-proto 命令) |
快速开始
1. 安装
# 创建新项目
dotnet new console -n MyGameServer
cd MyGameServer
# 方式一:使用元包(推荐,一次性引用所有运行时模块)
dotnet add package T2FGame
# 方式二:按需引用单独模块
dotnet add package T2FGame.Core
dotnet add package T2FGame.Action
dotnet add package T2FGame.Network.Socket
dotnet add package T2FGame.Cluster.Orleans
dotnet add package T2FGame.Persistence.MongoDB
dotnet add package T2FGame.Cache.Redis # 可选:Redis 分布式缓存
可选:Source Generator(编译时优化)
Source Generator 是可选的编译时优化,可消除运行时反射,提升性能:
<ItemGroup>
<PackageReference Include="T2FGame.CodeGen.Action" Version="1.0.0"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
<PackageReference Include="T2FGame.CodeGen.Protocol" Version="1.0.0"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
使用 Source Generator 后,需要调用生成的注册方法:
// 使用 Source Generator 生成的注册(推荐)
services.AddT2FGameActionGenerated();
// 或使用运行时反射注册(无需 Source Generator)
services.AddT2FGameAction(typeof(UserController).Assembly);
可选:开发工具
# 安装 CLI 工具(全局)
dotnet tool install -g T2FGame.Tools.Cli
# 导出 .proto 文件
t2f-proto export -a ./bin/Release/net9.0/MyGameServer.dll -o ./proto
# 生成客户端 SDK
t2f-proto sdk -a ./bin/Release/net9.0/MyGameServer.dll -o ./client-sdk -n MyGame.Client
或在项目中引用工具库:
<PackageReference Include="T2FGame.Tools" Version="1.0.0" />
2. 定义 Action
[ActionController(cmd: 1)] // 用户模块
public class UserController
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[ActionMethod(subCmd: 1, description: "用户登录")]
public async Task<LoginResponse> Login(LoginRequest request, FlowContext context)
{
var result = await _userService.LoginAsync(request.Username, request.Password);
context.SetAuthenticated(result.UserId);
return new LoginResponse
{
UserId = result.UserId,
Token = result.Token
};
}
[ActionMethod(subCmd: 2, requireAuth: true)]
public async Task<UserInfo> GetUserInfo(FlowContext context)
{
return await _userService.GetByIdAsync(context.UserId);
}
}
3. 配置服务器
var host = Host.CreateDefaultBuilder(args)
// 配置 Orleans 集群
.UseT2FGameCluster(options =>
{
options.ClusterId = "MyGameCluster";
options.ServiceId = "MyGame";
// 生产环境使用 MongoDB
options.ClusteringProvider = ClusteringProviderType.MongoDB;
options.PersistenceProvider = PersistenceProviderType.MongoDB;
options.MongoConnectionString = "mongodb://localhost:27017";
options.MongoDatabaseName = "MyGame";
})
.ConfigureServices((context, services) =>
{
// 注册 Action(二选一)
// 方式一:运行时反射扫描
services.AddT2FGameAction(typeof(UserController).Assembly);
// 方式二:Source Generator 生成(需要引用 T2FGame.CodeGen.Action)
// services.AddT2FGameActionGenerated();
// 注册 Pipeline
services.AddActionPipeline();
// 注册 MongoDB 持久化
services.AddMongoDbPersistence(options =>
{
options.ConnectionString = "mongodb://localhost:27017";
options.DatabaseName = "MyGame";
});
// 注册游戏服务器
services.AddT2FGameServer(options =>
{
options.ServerId = "game-server-1";
options.ServerName = "游戏服务器1";
});
// 注册网络服务(TCP)
services.AddT2FGameSocket();
// 或使用其他协议组合
// services.AddT2FGameWebSocket(); // 仅 WebSocket
// services.AddT2FGameUdp(); // 仅 UDP
// services.AddT2FGameDualProtocol(); // TCP + WebSocket
// services.AddT2FGameAllProtocols(); // TCP + UDP + WebSocket
// 注册广播服务
services.AddT2FGameBroadcast();
})
.Build();
await host.RunAsync();
4. 定义协议消息
T2FGame 使用 protobuf-net 进行序列化,通过特性标记消息类:
using ProtoBuf;
using T2FGame.Protocol.Codec;
[ProtoContract]
public class LoginRequest : IProtoMessage
{
[ProtoMember(1)]
public string Username { get; set; }
[ProtoMember(2)]
public string Password { get; set; }
}
[ProtoContract]
public class LoginResponse : IProtoMessage
{
[ProtoMember(1)]
public long UserId { get; set; }
[ProtoMember(2)]
public string Token { get; set; }
}
[ProtoContract]
public class UserInfo : IProtoMessage
{
[ProtoMember(1)]
public long UserId { get; set; }
[ProtoMember(2)]
public string Nickname { get; set; }
[ProtoMember(3)]
public int Level { get; set; }
}
使用 T2FGame.CodeGen.Protocol Source Generator,可以自动从这些类生成 .proto 文件供其他语言客户端使用。
与 ioGame 对比
| ioGame 概念 | T2FGame 对应 | 说明 |
|---|---|---|
| BarSkeleton | ActionPipeline | 业务处理骨架 |
| ActionController | ActionController | Action 控制器 |
| ActionMethod | ActionMethod | Action 方法 |
| FlowContext | FlowContext | 请求上下文 |
| BrokerServer | BrokerGrain | 消息代理 |
| BrokerClient | GameServerGrain | 游戏逻辑服务器 |
| ExternalServer | Network.Socket | 外部网关 |
| CmdMerge | CmdKit.GetMergeCmd | 命令路由合并 |
| RoomKit | T2FGame.Room | 房间模块 |
技术栈
- .NET 9:最新 LTS 版本
- Microsoft Orleans 9.x:分布式 Actor 框架
- SuperSocket 2.x:高性能网络库
- StackExchange.Redis:高性能 Redis 客户端
- MongoDB Driver 3.x:MongoDB 官方驱动
- protobuf-net:Protocol Buffers 序列化
环境要求
- .NET 9.0 SDK
- MongoDB 4.4+(推荐副本集模式)
- Redis 6.0+(可选,用于分布式缓存和限流)
项目结构
T2FGame/
├── src/
│ ├── T2FGame/ # 元包
│ ├── T2FGame.Core/ # 核心库
│ ├── T2FGame.Protocol/ # 协议层
│ ├── T2FGame.Action/ # Action 层
│ ├── T2FGame.Network.Socket/ # 网络层
│ ├── T2FGame.Cluster.Orleans/ # 集群层
│ ├── T2FGame.Room/ # 房间模块
│ ├── T2FGame.Cache.Redis/ # Redis 缓存
│ ├── T2FGame.Persistence.MongoDB/ # MongoDB 持久化
│ ├── T2FGame.CodeGen/ # 源生成器基础框架
│ ├── T2FGame.CodeGen.Action/ # Action 源生成器
│ ├── T2FGame.CodeGen.Protocol/ # 协议源生成器
│ ├── T2FGame.Tools/ # 开发工具库
│ └── T2FGame.Tools.Cli/ # CLI 工具
├── samples/ # 示例项目
├── tests/ # 测试项目
├── Directory.Packages.props # 中央包管理
├── Directory.Build.props # 公共构建配置
└── T2FGame.sln # 解决方案文件
文档
每个模块都有独立的 README 文档,详细说明用法:
运行时模块
- T2FGame.Core - DDD 基础设施
- T2FGame.Protocol - 协议定义
- T2FGame.Action - Action 框架
- T2FGame.Network.Socket - 网络通信
- T2FGame.Cluster.Orleans - 分布式集群
- T2FGame.Room - 房间系统
- T2FGame.Cache.Redis - Redis 分布式缓存
- T2FGame.Persistence.MongoDB - MongoDB 持久化
代码生成模块
- T2FGame.CodeGen - 源生成器基础框架
- T2FGame.CodeGen.Action - Action 源生成器
- T2FGame.CodeGen.Protocol - 协议源生成器
开发工具
- T2FGame.Tools - 开发工具库
构建
# 还原依赖
dotnet restore
# 构建
dotnet build
# 运行测试
dotnet test
Source Generator 使用指南
T2FGame 提供两个可选的 Source Generator,用于编译时代码生成,消除运行时反射开销。
T2FGame.CodeGen.Action
功能: 编译时生成 Action 调用器和注册表,消除运行时反射。
引用方式:
<PackageReference Include="T2FGame.CodeGen.Action" Version="1.0.0"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
生成内容:
GeneratedActionInvoker.g.cs- 零反射的 Action 调用器GeneratedActionRegistry.g.cs- 编译时生成的 Action 注册表
使用方式:
// 注册生成的 Action(推荐)
services.AddT2FGameActionGenerated();
T2FGame.CodeGen.Protocol
功能: 从 [ProtoContract] 标记的类型自动生成 protobuf-net 配置和 .proto 文件。
引用方式:
<PackageReference Include="T2FGame.CodeGen.Protocol" Version="1.0.0"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
支持的类型:
class/record- 生成 message 定义enum- 生成 enum 定义
示例:
[ProtoContract]
public class LoginRequest
{
[ProtoMember(1)] public string Username { get; set; }
[ProtoMember(2)] public string Password { get; set; }
}
[ProtoContract]
public enum UserStatus
{
Offline = 0,
Online = 1,
Busy = 2
}
生成的 .proto 文件:
message LoginRequest {
string username = 1;
string password = 2;
}
enum UserStatus {
OFFLINE = 0;
ONLINE = 1;
BUSY = 2;
}
开发工具使用指南
CLI 工具 (T2FGame.Tools.Cli)
安装:
# 全局安装
dotnet tool install -g T2FGame.Tools.Cli
# 本地安装(项目级)
dotnet new tool-manifest
dotnet tool install T2FGame.Tools.Cli
命令:
# 导出 .proto 文件
t2f-proto export -a ./bin/Release/net9.0/MyGameServer.dll -o ./proto
# 导出所有嵌入资源(包括 TypeScript 等)
t2f-proto export -a ./MyGameServer.dll -o ./proto --all
# 生成客户端 SDK
t2f-proto sdk -a ./MyGameServer.dll -o ./client-sdk -n MyGame.Client
# 使用 protoc 生成其他语言代码
t2f-proto protoc -p ./proto -o ./generated -l java
# 查看版本信息
t2f-proto version
工具库 (T2FGame.Tools)
用于在代码中调用导出功能:
using T2FGame.Tools;
using T2FGame.Tools.ClientSdk;
// 导出 .proto 文件(支持多程序集)
var exporter = new ProtoExporter();
var result = exporter.Export(
new[] { "GameServer.dll", "SharedModule.dll" },
outputDirectory: "./proto");
// 生成客户端 SDK(支持多程序集)
var generator = new ClientSdkGenerator();
var sdkResult = generator.Generate(
new[] { "GameServer.dll", "SharedModule.dll" },
outputDirectory: "./client-sdk",
new ClientSdkOptions { ClientNamespace = "MyGame.Client" });
生成的客户端 SDK 包括:
*Action.cs- Action 调用封装,提供类型安全的 APIListener.cs- 广播消息监听器GameCode.cs- 错误码定义
致谢
- ioGame - 灵感来源
- Microsoft Orleans - 分布式 Actor 框架
- SuperSocket - 网络通信库
- StackExchange.Redis - Redis 客户端
Learn more about Target Frameworks and .NET Standard.
-
net9.0
- T2FGame.Action (>= 1.0.9)
- T2FGame.Cache.Redis (>= 1.0.9)
- T2FGame.Cluster.Orleans (>= 1.0.9)
- T2FGame.Core (>= 1.0.9)
- T2FGame.Network.Socket (>= 1.0.9)
- T2FGame.Persistence.MongoDB (>= 1.0.9)
- T2FGame.Protocol (>= 1.0.9)
- T2FGame.Room (>= 1.0.9)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on T2FGame:
| Package | Downloads |
|---|---|
|
T2FGame.Samples.GameServer
A high-performance game server framework |
GitHub repositories
This package is not used by any popular GitHub repositories.