T2FGame.Network.Socket 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package T2FGame.Network.Socket --version 1.0.0
                    
NuGet\Install-Package T2FGame.Network.Socket -Version 1.0.0
                    
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.Network.Socket" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="T2FGame.Network.Socket" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="T2FGame.Network.Socket" />
                    
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.Network.Socket --version 1.0.0
                    
#r "nuget: T2FGame.Network.Socket, 1.0.0"
                    
#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.Network.Socket@1.0.0
                    
#: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.Network.Socket&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=T2FGame.Network.Socket&version=1.0.0
                    
Install as a Cake Tool

T2FGame.Network.Socket

T2FGame 框架的网络层,基于 SuperSocket 实现高性能 TCP 通信。

功能特性

  • 高性能 TCP 服务器:基于 SuperSocket 2.x
  • 自定义协议编解码:支持变长消息、心跳检测
  • 会话管理:GameSession 生命周期管理
  • 消息分发:与 Action 框架无缝集成
  • 推送/广播:支持主动推送消息给客户端

安装

<PackageReference Include="T2FGame.Network.Socket" />

协议格式

消息包结构

+--------+--------+--------+--------+--------+--------+
| Length |  Type  |  Cmd   | SubCmd | MsgId  |  Data  |
+--------+--------+--------+--------+--------+--------+
|   4    |   1    |   2    |   2    |   4    |   N    |
+--------+--------+--------+--------+--------+--------+

- Length: 整个包的长度(不含自身4字节)
- Type: 消息类型(请求/响应/推送/心跳)
- Cmd: 主命令
- SubCmd: 子命令
- MsgId: 消息ID(用于请求/响应配对)
- Data: Protobuf 序列化的业务数据

消息类型

public enum CommandType : byte
{
    Request = 0,      // 客户端请求
    Response = 1,     // 服务器响应
    Push = 2,         // 服务器推送
    Heartbeat = 3,    // 心跳
    Error = 4         // 错误响应
}

快速开始

1. 创建服务器

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        // 注册 Action 框架
        services.AddActionMethodRegistry(options =>
        {
            options.ScanAssemblies(typeof(UserController).Assembly);
        });
        services.AddActionPipeline();

        // 注册网络服务
        services.AddT2FGameSocket(options =>
        {
            options.Port = 9000;
            options.MaxConnections = 10000;
            options.IdleTimeout = TimeSpan.FromMinutes(5);
        });
    })
    .Build();

await host.RunAsync();

2. 配置选项

services.AddT2FGameSocket(options =>
{
    // 监听设置
    options.Host = "0.0.0.0";
    options.Port = 9000;

    // 连接限制
    options.MaxConnections = 10000;
    options.MaxPackageLength = 65535;

    // 超时设置
    options.IdleTimeout = TimeSpan.FromMinutes(5);
    options.HeartbeatInterval = TimeSpan.FromSeconds(30);

    // 缓冲区设置
    options.ReceiveBufferSize = 4096;
    options.SendBufferSize = 4096;
});

核心组件

GameSession(游戏会话)

public class GameSession
{
    public string SessionId { get; }
    public long UserId { get; set; }
    public bool IsAuthenticated { get; }
    public DateTime LastActiveTime { get; }
    public ConnectionState State { get; }

    // 发送消息
    public ValueTask SendAsync(IMessage message, int cmdMerge);
    public ValueTask SendRawAsync(byte[] data);

    // 会话属性
    public T? GetAttribute<T>(string key);
    public void SetAttribute<T>(string key, T value);
}

SocketActionDispatcher(消息分发器)

public class SocketActionDispatcher
{
    // 处理接收到的数据包
    public async Task HandleAsync(
        string sessionId,
        GamePackage package,
        Func<byte[], ValueTask> sendCallback,
        CancellationToken cancellationToken = default);

    // 会话管理
    public GameSession GetOrCreateSession(string sessionId);
    public GameSession? GetSession(string sessionId);
    public bool RemoveSession(string sessionId);
    public int SessionCount { get; }
}

GamePackageCodec(编解码器)

// 编码请求
byte[] encoded = GamePackageCodec.EncodeRequest(cmdMerge, data, messageId);

// 编码响应
byte[] encoded = GamePackageCodec.EncodeResponse(cmdMerge, data, messageId);

// 编码推送
byte[] encoded = GamePackageCodec.EncodePush(cmdMerge, data);

// 编码错误
byte[] encoded = GamePackageCodec.EncodeErrorResponse(
    cmdMerge, messageId, errorCode, errorMessage);

// 编码心跳
byte[] encoded = GamePackageCodec.EncodeHeartbeat(messageId);

消息推送

单播推送

public class NotificationService
{
    private readonly SocketActionDispatcher _dispatcher;

    public async Task SendToUserAsync(long userId, IMessage message, int cmdMerge)
    {
        var session = FindSessionByUserId(userId);
        if (session != null)
        {
            await session.SendAsync(message, cmdMerge);
        }
    }
}

广播推送

public class BroadcastService
{
    private readonly SocketActionDispatcher _dispatcher;

    public async Task BroadcastAsync(IMessage message, int cmdMerge)
    {
        var sessions = _dispatcher.GetAllSessionIds();
        var data = GamePackageCodec.EncodePush(cmdMerge, message.ToByteArray());

        foreach (var sessionId in sessions)
        {
            var session = _dispatcher.GetSession(sessionId);
            if (session?.IsAuthenticated == true)
            {
                await session.SendRawAsync(data);
            }
        }
    }
}

组播推送

public async Task SendToGroupAsync(
    IEnumerable<long> userIds,
    IMessage message,
    int cmdMerge)
{
    var data = GamePackageCodec.EncodePush(cmdMerge, message.ToByteArray());

    foreach (var userId in userIds)
    {
        var session = FindSessionByUserId(userId);
        if (session != null)
        {
            await session.SendRawAsync(data);
        }
    }
}

SocketFlowContext

网络层的 FlowContext 实现:

public class SocketFlowContext : FlowContext
{
    public override string SessionId { get; }
    public override long UserId { get; }
    public override bool IsAuthenticated { get; }
    public override int CmdMerge { get; }
    public override int MessageId { get; }

    // 发送响应
    public override async ValueTask SendAsync(IMessage response)
    {
        var data = GamePackageCodec.EncodeResponse(
            CmdMerge, response.ToByteArray(), MessageId);
        await _sendCallback(data);
    }

    // 发送原始数据
    public override ValueTask SendRawAsync(byte[] data)
    {
        return _sendCallback(data);
    }
}

心跳机制

服务器自动处理心跳包:

// 客户端发送心跳请求
// Type = Heartbeat, MsgId = 自增ID

// 服务器自动回复心跳响应
// Type = Heartbeat, MsgId = 相同ID

会话超时检测:

// 配置空闲超时
options.IdleTimeout = TimeSpan.FromMinutes(5);

// 超过5分钟无活动的会话将被自动断开

目录结构

T2FGame.Network.Socket/
├── Configuration/
│   └── SocketServerOptions.cs    # 服务器配置
├── Dispatcher/
│   └── SocketActionDispatcher.cs # 消息分发器
├── Protocol/
│   ├── GamePackage.cs            # 数据包结构
│   ├── GamePackageCodec.cs       # 编解码器
│   ├── GamePackageFilter.cs      # SuperSocket 过滤器
│   └── CommandType.cs            # 消息类型枚举
├── Session/
│   ├── GameSession.cs            # 游戏会话
│   └── SessionManager.cs         # 会话管理器
├── Context/
│   └── SocketFlowContext.cs      # Socket 上下文实现
└── Extensions/
    └── ServiceCollectionExtensions.cs # 服务注册

性能优化建议

  1. 连接池:复用 byte[] 缓冲区,减少 GC 压力
  2. 批量发送:合并多个小消息,减少系统调用
  3. 异步处理:使用 ValueTask 避免不必要的 Task 分配
  4. 会话缓存:缓存频繁访问的会话属性
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 (1)

Showing the top 1 NuGet packages that depend on T2FGame.Network.Socket:

Package Downloads
T2FGame

T2FGame Framework - A high-performance distributed game server framework inspired by ioGame. This meta-package includes all T2FGame components.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.9 428 12/11/2025
1.0.8 424 12/11/2025
1.0.7 426 12/11/2025
1.0.6 426 12/11/2025
1.0.5 441 12/10/2025
1.0.4 440 12/10/2025
1.0.3 457 12/9/2025
1.0.2 351 12/8/2025
1.0.1 489 12/1/2025
1.0.0 179 11/28/2025
0.0.1 357 12/8/2025