SAEA.FileSocket 26.11.16.1

dotnet add package SAEA.FileSocket --version 26.11.16.1
                    
NuGet\Install-Package SAEA.FileSocket -Version 26.11.16.1
                    
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="SAEA.FileSocket" Version="26.11.16.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SAEA.FileSocket" Version="26.11.16.1" />
                    
Directory.Packages.props
<PackageReference Include="SAEA.FileSocket" />
                    
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 SAEA.FileSocket --version 26.11.16.1
                    
#r "nuget: SAEA.FileSocket, 26.11.16.1"
                    
#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 SAEA.FileSocket@26.11.16.1
                    
#: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=SAEA.FileSocket&version=26.11.16.1
                    
Install as a Cake Addin
#tool nuget:?package=SAEA.FileSocket&version=26.11.16.1
                    
Install as a Cake Tool

SAEA.FileSocket - 高性能文件传输组件 📁

NuGet version License

English Version | 中文版

基于 SAEA.Sockets 的高性能文件传输组件,采用异步 IO,支持大文件分块传输、断点续传、实时进度监控。

⚡ 零拷贝内核:构建于 SAEA.Sockets 的 Span/Memory 零拷贝收发与内存池通道之上,显著降低分配与 GC。

快速导航 🧭

章节 内容
⚡ 30秒快速开始 最简单的上手示例
🎯 核心特性 组件的主要功能
📐 架构设计 传输流程与协议
💡 应用场景 何时选择 SAEA.FileSocket
📊 性能对比 传输性能数据
❓ 常见问题 FAQ 快速解答
🔧 核心类 主要类一览
📝 使用示例 详细代码示例

30秒快速开始 ⚡

最快上手方式,只需3步即可实现文件传输:

Step 1: 安装 NuGet 包

dotnet add package SAEA.FileSocket

Step 2: 创建文件接收服务器(仅需6行代码)

using SAEA.FileSocket;

var fileTransfer = new FileTransfer(@"C:\ReceivedFiles", port: 39654);
fileTransfer.OnReceiveEnd += (path) => Console.WriteLine($"接收完成: {path}");
fileTransfer.Start();

Step 3: 发送文件

fileTransfer.SendFile(@"C:\Data\video.mp4", "192.168.1.100");

就这么简单! 🎉 你已经实现了一个支持大文件、断点续传的高性能文件传输系统。


核心特性 🎯

特性 说明 优势
🚀 跨平台异步 IO 基于 SAEA.Sockets 异步 IO 支持高并发文件传输
📦 大文件支持 分块传输机制 支持 TB 级超大文件
🔄 断点续传 offset 参数从指定位置续传 网络中断可恢复
📊 实时进度 发送/接收速度、数据量统计 可视化监控传输状态
💓 心跳保活 10秒心跳间隔保持连接 自动检测连接状态
📡 处理器链 接收方向由 SAEA.Sockets.Pipeline 驱动,ConfigurePipeline 按需追加处理器 无需改动组件即可扩展接收逻辑
🤝 四阶段握手 请求/允许/拒绝/数据流协议 安全可靠的传输控制

架构设计 📐

组件架构图

┌─────────────────────────────────────────────────────────────┐
│                   SAEA.FileSocket 架构                       │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────────────────────────────────────────────┐  │
│  │                   FileTransfer                         │  │
│  │              (文件传输协调主类)                        │  │
│  └───────────────────────┬──────────────────────────────┘  │
│                          │                                  │
│           ┌──────────────┴──────────────┐                  │
│           │                             │                   │
│  ┌────────▼────────┐          ┌────────▼────────┐        │
│  │      Client     │          │      Server      │        │
│  │    (发送端)     │          │    (接收端)      │        │
│  └────────┬────────┘          └────────┬────────┘        │
│           │                             │                   │
│           │     ┌───────────────┐       │                   │
│           └────►│ FileMessage   │◄──────┘                  │
│                 │  (消息模型)   │                           │
│                 └───────┬───────┘                          │
│                         │                                   │
│              ┌──────────┴──────────┐                       │
│              │                     │                        │
│       ┌──────▼──────┐      ┌───────▼──────┐               │
│       │  Request    │      │   Chunk      │               │
│       │  (请求)     │      │   (数据块)   │               │
│       └─────────────┘      └──────────────┘               │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐  │
│  │  SAEA.Sockets.Pipeline (拆帧 / 解码 / 处理器链)      │  │
│  └─────────────────────────────────────────────────────┘  │
│  ┌─────────────────────────────────────────────────────┐  │
│  │               SAEA.Sockets (异步 IO)                │  │
│  └─────────────────────────────────────────────────────┘  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

文件传输流程图

文件传输完整流程:

发送端                                    接收端
  │                                         │
  │  1. SendFile(fileName, targetIp)        │
  │────────────────────────────────────────►│
  │                                         │
  │  2. 请求发送 (RequestMessage)            │
  │     ├── FileName                        │
  │     └── FileLength                      │
  │────────────────────────────────────────►│
  │                                         │
  │                              3. 请求处理器
  │                                 ├── Server.Allow(id)  允许
  │                                 └── Server.Refuse(id) 拒绝
  │                                         │
  │  4. 允许接收 (AllowReceive)             │
  │◄────────────────────────────────────────│
  │                                         │
  │  5. 分块发送数据流                        │
  │     ┌─────────────────────────────────┐ │
  │     │ Chunk 1 (100KB)                 │ │
  │     │────────────────────────────────►│ │
  │     │ Chunk 2 (100KB)                 │ │
  │     │────────────────────────────────►│ │
  │     │ Chunk 3 (100KB)                 │ │
  │     │────────────────────────────────►│ │
  │     │ ...                             │ │
  │     │ Chunk N (剩余部分)              │ │
  │     │────────────────────────────────►│ │
  │     └─────────────────────────────────┘ │
  │                                         │
  │                              6. 写入文件 (File.WriteAllText)
  │                                         │
  │                              7. 内置接收处理器落盘
  │                                 └── FileTransfer 触发 OnReceiveEnd
  │                                         │
  │  8. 发送完成回调                          │
  │◄────────────────────────────────────────│
  │                                         │

断点续传流程:

  │  SendFile(fileName, offset)             │
  │────────────────────────────────────────►│
  │  从 offset 位置继续发送                   │
  │  ├── 跳过已传输部分                       │
  │  └── 只发送剩余数据                       │
  │────────────────────────────────────────►│

传输协议详解

┌─────────────────────────────────────────────────────────────┐
│                    四阶段握手协议                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  阶段1: 请求 (RequestMessage)                               │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ 消息类型: Request                                    │   │
│  │ 内容: FileName + FileLength                         │   │
│  │ 说明: 发送端请求发送文件                              │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  阶段2: 响应 (ResponseMessage)                              │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ AllowReceive: 允许接收                               │   │
│  │ RefuseReceive: 拒绝接收                              │   │
│  │ 说明: 接收端决定是否接收                              │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  阶段3: 数据流 (DataMessage)                                │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ 分块大小: 默认 100KB                                  │   │
│  │ 发送方式: SendAsync 异步发送                          │   │
│  │ 说明: 分块传输文件内容                                │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  阶段4: 完成 (Complete)                                     │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ 触发: 内置接收处理器收齐分块后 FileTransfer 抛 OnReceiveEnd │   │
│  │ 动作: 保存文件、清理资源                              │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

应用场景 💡

✅ 适合使用 SAEA.FileSocket 的场景

场景 描述 推荐理由
📁 局域网文件共享 快速传输大文件 跨平台异步 IO,局域网可接近线速
💾 数据备份 定时备份大数据 断点续传保证可靠性
🔄 文件同步 多服务器文件同步 分块传输,支持大文件
🎬 视频传输 大视频文件传输 支持 TB 级文件
🏢 企业内部传输 安全内网文件分发 私有协议,可控安全
☁️ 云端数据迁移 跨服务器数据迁移 高吞吐量,进度可监控

❌ 不适合的场景

场景 推荐替代方案
需要加密传输 使用 SAEA.Sockets + SSL
跨互联网传输 使用 HTTPS 或 FTPS
需要权限验证 自行添加认证层

性能对比 📊

传输性能数据

指标 SAEA.FileSocket 传统 HTTP 上传 优势
传输速度 高(局域网可达线速) 中等 更高吞吐
最大文件 支持 TB 级 受内存限制 超大文件
断点续传 ✅ 原生支持 ❌ 需要额外实现 可靠性强
内存占用 低 (分块传输) 高 (全量缓存) 内存友好
并发传输 支持 需要多线程 高并发

分块传输效率

文件大小 默认块大小 (100KB) 推荐块大小 传输耗时 (1Gbps)
100MB 1000 块 100KB ~1 秒
1GB 10000 块 1MB ~10 秒
10GB 100000 块 10MB ~100 秒
100GB 1000000 块 10MB ~17 分钟

💡 提示: 可根据网络环境和文件大小调整 bufferSize 参数优化传输效率。

与其他方案对比

方案 断点续传 进度监控 大文件支持 实现复杂度
SAEA.FileSocket ✅ ✅ ✅ TB级 ⭐ 简单
FTP ✅ ❌ ✅ ⭐⭐ 中等
HTTP 上传 ❌ ✅ ❌ 内存限制 ⭐⭐ 中等
自定义 Socket 需实现 需实现 需实现 ⭐⭐⭐ 复杂

常见问题 ❓

Q1: 如何实现断点续传?

A: 使用 offset 参数从指定位置继续传输:

// 记录已传输的位置
long lastOffset = GetLastOffset(fileName);

// 从断点继续发送
client.SendFile(fileName, lastOffset, (success) => 
{
    if (success)
        Console.WriteLine("续传成功");
});

// 接收端会从 offset 位置继续写入

Q2: 如何调整传输块大小?

A: 在构造函数中设置 bufferSize 参数:

// 小文件或网络不稳定:使用较小块
var fileTransfer = new FileTransfer(path, port, bufferSize: 50 * 1024);

// 大文件或高速网络:使用较大块
var fileTransfer = new FileTransfer(path, port, bufferSize: 1024 * 1024);  // 1MB

Q3: 如何监控传输进度?

A: 使用 OnDisplay 事件:

fileTransfer.OnDisplay += (info) => 
{
    Console.WriteLine(info);  // 包含发送/接收速度
};

fileTransfer.OnReceiveEnd += (filePath) => 
{
    Console.WriteLine($"接收完成: {filePath}");
};

Q4: 如何拒绝接收特定文件?

A: 用 ConfigurePipeline 在接收链上追加自己的处理器,按业务规则调用 Refuse 或放行。 装配回调必须在 Start() 之前赋值,服务启动后再赋值会抛 InvalidOperationException:

using SAEA.Common.Serialization;
using SAEA.FileSocket;
using SAEA.FileSocket.Model;
using SAEA.Sockets.Base;
using SAEA.Sockets.Model;
using SAEA.Sockets.Pipeline;

var server = new Server(port: 39654);

server.ConfigurePipeline = (id, pipeline) =>
{
    pipeline.AddLast(new RejectLargeFileHandler(server));
};

server.Start();

sealed class RejectLargeFileHandler : InboundHandlerAdapter
{
    private readonly Server _server;

    public RejectLargeFileHandler(Server server)
    {
        _server = server;
    }

    public override async Task ChannelReadAsync(IChannelHandlerContext ctx, object msg)
    {
        var protocal = msg as BaseSocketProtocal;
        if (protocal != null && protocal.Type == (byte)SocketProtocalType.RequestSend)
        {
            var file = SerializeHelper.PBDeserialize<FileMessage>(protocal.Content.ToArray());
            if (file.Length > 1024L * 1024 * 1024)
            {
                // 拒绝后不再向下游转发,本次请求到此为止。
                _server.Refuse(ctx.Channel.Id);
                return;
            }
        }

        await ctx.FireChannelReadAsync(msg);
    }
}

放行时调用 _server.Allow(ctx.Channel.Id),再 await ctx.FireChannelReadAsync(msg) 让内置处理器继续处理请求帧。

Q5: 支持同时传输多个文件吗?

A: 支持。多个 Client 实例各自建立连接即可并发;同一个 Client 串行发送:

// 方式1: 使用 FileTransfer 顺序发送
fileTransfer.SendFile(file1, targetIp);
fileTransfer.SendFile(file2, targetIp);

// 方式2: 创建多个 Client 并发发送,连接参数在构造函数上
var client1 = new Client(bufferSize: 100 * 1024, ip: "192.168.1.100", port: 39654);
var client2 = new Client(bufferSize: 100 * 1024, ip: "192.168.1.100", port: 39654);
client1.Connect();
client2.Connect();
client1.SendFile(file1, 0, success => Console.WriteLine("文件1: " + success));
client2.SendFile(file2, 0, success => Console.WriteLine("文件2: " + success));

Q6: 传输中断后如何恢复?

A: FileSocket 支持断点续传,只需记录已传输的字节数:

// 1. 定期保存已传输位置
long savedOffset = GetTransferredBytes(fileName);
SaveProgress(fileName, savedOffset);

// 2. 中断后从保存位置恢复
long lastOffset = LoadProgress(fileName);
client.SendFile(fileName, lastOffset, callback);

Q7: 如何自定义接收路径?

A: 接收路径由 FileTransfer 的 filePath 参数决定,Server 本身不落盘:

// 收到的文件会保存到 C:\CustomPath 下,文件名沿用发送端的文件名
var fileTransfer = new FileTransfer(@"C:\CustomPath", port: 39654);
fileTransfer.Start();

核心类 🔧

类名 说明
FileTransfer 文件传输主协调类,同时支持发送和接收
Client 文件发送客户端,用于主动发送文件
Server 文件接收服务器,提供 Allow / Refuse 应答与 ConfigurePipeline 扩展点
FileMessage 文件消息数据模型,定义传输协议
FileMessageDecoder 入站解码器,把完整帧解成协议对象并丢弃心跳帧
FileMessageEncoder 出站编码器,把协议对象写成完整线格式帧
FileFrameSplitter 线格式拆帧配置,统一帧长上限口径

使用示例 📝

基础文件传输

using SAEA.FileSocket;

var fileTransfer = new FileTransfer(@"C:\ReceivedFiles", port: 39654);

fileTransfer.OnReceiveEnd += (filePath) => 
    Console.WriteLine($"文件接收完成: {filePath}");

fileTransfer.OnDisplay += (info) => 
    Console.WriteLine($"传输状态: {info}");

fileTransfer.Start();
fileTransfer.SendFile(@"C:\Data\document.pdf", "192.168.1.100");

Server 端自定义处理

using SAEA.FileSocket;
using SAEA.Sockets.Pipeline;

var server = new Server(port: 39654, bufferSize: 100 * 1024);

// 接收链上追加自己的处理器;不追加时只走内置的文件落盘处理器。
server.ConfigurePipeline = (id, pipeline) =>
{
    pipeline.AddLast(new LoggingHandler());
};

server.Start();

sealed class LoggingHandler : InboundHandlerAdapter
{
    public override async Task ChannelReadAsync(IChannelHandlerContext ctx, object msg)
    {
        Console.WriteLine($"收到 {ctx.Channel.Id} 的消息:{msg.GetType().Name}");

        // 交回下游,内置处理器才能继续落盘。
        await ctx.FireChannelReadAsync(msg);
    }
}

Client 端发送(带回调)

using SAEA.FileSocket;

// 目标地址在建连时确定,需先 Connect 再发送。
var client = new Client(bufferSize: 100 * 1024, ip: "192.168.1.100", port: 39654);

client.Connect();

client.SendFile(@"C:\Data\document.pdf", 0, success =>
{
    if (success)
        Console.WriteLine("发送成功");
    else
        Console.WriteLine("发送失败");
});

// 断点续传:offset 表示跳过前面已传输的字节数
long offset = 1024 * 1024 * 100;
client.SendFile(@"C:\Data\large_file.dat", offset, success =>
    Console.WriteLine($"续传结果: {success}"));

自定义缓冲区大小

using SAEA.FileSocket;

// 小缓冲区:网络不稳定场景
var smallBuffer = new FileTransfer(path, port, bufferSize: 50 * 1024);

// 大缓冲区:高速网络大文件场景
var largeBuffer = new FileTransfer(path, port, bufferSize: 1024 * 1024);

分块传输机制

参数 默认值 说明
bufferSize 100KB 每次传输的数据块大小
heartSpan 10秒 心跳保活间隔
发送方式 SendAsync 异步发送数据块
线程安全 Interlocked 线程安全计数

传输协议格式

FileSocket 使用四阶段握手协议:

┌──────────────┐     Request      ┌──────────────┐
│    发送端    │ ────────────────► │    接收端    │
│   (Client)   │                   │   (Server)   │
└──────────────┘                   └──────────────┘
       │                                  │
       │◄───── Allow/Refuse ─────────────│
       │                                  │
       │═══════ Data Chunks ═════════════►│
       │                                  │
       │◄───── Complete ──────────────────│

依赖项

包名 版本 说明
SAEA.Sockets 26.11.5.1 Socket 通信框架
SAEA.Sockets.Pipeline 26.11.5.1 拆帧、编解码与处理器链
SAEA.Common 26.11.5.1 公共工具类

更多资源


许可证

Apache License 2.0

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos 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 SAEA.FileSocket:

Package Downloads
Xxyter.CSharp

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
26.11.16.1 90 11/16/2026
26.10.8.1 123 10/8/2026
26.4.23.1 263 4/23/2026
26.4.22.1 143 4/21/2026
7.26.4.21 154 4/20/2026
7.26.4.20 131 4/20/2026
7.26.2.2 177 2/2/2026
7.26.1.27 154 1/27/2026
7.26.1.25 157 1/25/2026
7.25.2.19 326 2/19/2025
7.25.2.18 251 2/18/2025
7.25.2.13 260 2/13/2025
7.25.2.11 247 2/11/2025
7.24.8.4 279 8/4/2024
7.23.9.24 303 9/24/2023
7.0.3.19 446 3/19/2023
7.0.0.3 726 2/27/2022
7.0.0.2 592 12/5/2021
7.0.0.1 539 11/28/2021
6.2.6.7 825 9/19/2021
Loading failed

This is a high-performance file transfer component based on SAEA.Sockets.
这是一个基于SAEA.Sockets的高性能文件传输组件