BugFree.Net 1.0.250816.1339

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

BugFree.Net

一个面向 .NET 8 的轻量网络时间(NTP)组件,包含:

  • NTP 客户端:多次采样、统计平均偏移与最小网络时延,并估计上下行延迟不对称(asymmetry)。
  • NTP 服务器:多线程/通道驱动的高吞吐 UDP 响应,返回标准 48 字节 NTP 报文。
  • 跨平台高精度时间源:内部在 Windows 使用 GetSystemTimePreciseAsFileTime,在 Linux 使用 clock_gettime。

命名空间:BugFree.Net.NTP

提示:校时(写系统时间)需要管理员/root 权限;并请合理使用公共 NTP 资源,避免高频请求。

功能特性

  • NTP 客户端(RFC 5905 思想):
    • 多次采样,输出平均时间偏移 averageOffset、最小网络时延 minDelay、上下行延迟误差 asymmetry。
    • 可配置服务器地址与端口(默认 123)。
    • 提供一键同步系统时间的方法(需管理员/root)。
  • 轻量 NTP 服务器:
    • UDP Socket + 有界 Channel + 多 Worker,高优先级线程处理,缓冲池复用,减少 GC 压力。
    • 支持 IPv4/IPv6,默认端口 12345(非特权端口,便于开发测试)。
  • 高精度时钟(内部使用):
    • Windows:GetSystemTimePreciseAsFileTime。
    • Linux:clock_gettime。
  • 纯托管代码,零第三方依赖。

安装

目前项目以源码/本地包为主,推荐以下两种方式之一:

  1. 作为项目引用
  • 将本仓库中的 BugFree.Net/BugFree.Net.csproj 作为 ProjectReference 引入你的解决方案。
  1. 打本地 NuGet 包并引用
  • 在仓库根目录执行(Windows PowerShell):
dotnet pack .\BugFree.Net\BugFree.Net.csproj -c Release -o .\nupkgs
# 在你的应用项目中引用本地包源
dotnet add <YourProject>.csproj package BugFree.Net --source .\nupkgs

快速上手

1) 查询 NTP 并计算平均偏移

using System;
using BugFree.Net.NTP;

class Program
{
		static void Main()
		{
				var client = new NTPClient { Server = "pool.ntp.org", Port = 123 };

				// 采样 5 次:一般 4~8 次即可,网络不稳定可适当增加
				var (averageOffset, minDelay, asymmetry) = client.GetAverageNetworkTimeOffset(5);

				Console.WriteLine($"Avg offset: {averageOffset.TotalMilliseconds:F3} ms");
				Console.WriteLine($"Min delay: {minDelay.TotalMilliseconds:F3} ms");
				Console.WriteLine($"Asymmetry: {asymmetry.TotalMilliseconds:F3} ms");

				var correctedUtc = DateTime.UtcNow + averageOffset;
				Console.WriteLine($"Corrected UTC: {correctedUtc:O}");
		}
}

2) 同步系统时间(需管理员/root)

using BugFree.Net.NTP;

var client = new NTPClient { Server = "pool.ntp.org" };
// 将根据多次采样的平均偏移修正系统 UTC 时间
client.SyncSystemTime(sampleCount: 5);

注意:

  • Windows 需要以管理员权限运行进程;Linux 需要 root/sudo,内部通过 /bin/date 设置时间。
  • 某些系统守护进程(如 Windows Time、chronyd/ntpd)可能会再次同步覆盖,请按需协调。

3) 启动一个轻量 NTP 服务器

using System;
using BugFree.Net.NTP;

class Program
{
		static void Main()
		{
				using var server = new NTPServer(useIPv6: false);
				server.Port = 12345;  // 默认 12345;若改为 123,在 Linux 上需要 root 才能绑定 <1024 端口
				server.Start(workers: 4);

				Console.WriteLine("NTP server running on udp://0.0.0.0:12345, press Enter to exit...");
				Console.ReadLine();
		}
}

然后可将客户端 Server 指向该主机(本机可用 127.0.0.1 或内网 IP)。

API 摘要

命名空间:BugFree.Net.NTP

  • public class NTPClient

    • string Server { get; set; } NTP 服务器地址或 IP。
    • int Port { get; set; } = 123 服务器端口。
    • (TimeSpan averageOffset, TimeSpan minDelay, TimeSpan asymmetry) GetAverageNetworkTimeOffset(int sampleCount)
      • 多次采样,返回平均偏移、最小时延与上下行不对称估计。
      • 当没有任何有效响应时抛出异常。
    • void SyncSystemTime(int sampleCount)
      • 根据平均偏移修正系统 UTC 时间;需要管理员/root 权限。
  • public class NTPServer : IDisposable

    • int Port { get; set; } = 12345 监听端口(默认非特权)。
    • bool UseIPv6 { get; set; } 是否使用 IPv6 套接字。
    • void Start(int workers = 4, CancellationToken cancellationToken = default) 启动接收与多个处理线程。
    • void Dispose() 停止服务并释放资源(用于优雅关闭)。

错误与注意:

  • DNS 解析失败、超时、无效 NTP 响应会在采样中记录/抛出;当所有采样均失败时会抛出异常。
  • 绑定端口失败(端口占用/权限不足)会抛出 Socket 异常。
  • 写系统时间需要管理员/root,失败会抛出异常(包含错误码/标准错误输出)。

构建与本地打包

在仓库根目录下:

dotnet build .\BugFree.Net\BugFree.Net.csproj -c Release
dotnet pack  .\BugFree.Net\BugFree.Net.csproj -c Release -o .\nupkgs

将生成 nupkgs 目录,可在本机作为包源供其他项目引用。

运行环境

  • .NET 8(net8.0
  • Windows / Linux
  • 防火墙需允许 UDP 入/出站(客户端与服务器场景)。

最佳实践与建议

  • 采样次数:
    • 一般 4~5 次即可;网络不稳定或高精度需求可用 8 次以上,并剔除异常值。
  • 对公共 NTP 的礼貌:
    • 避免过短间隔的高频请求;优先使用就近/运营商/内网 NTP。
  • 服务器部署:
    • 开发测试使用 12345 端口;生产使用 123 端口需满足合规与权限要求。

附录:NTP 采样与同步建议

采样次数建议

  • 常用推荐值:3~8 次。
  • 取多次采样的平均值和最小延迟,可以有效过滤偶发的网络抖动和异常延迟。
  • 实际工程经验:
    • 3 次:最小,能初步过滤极端值,但抗干扰能力有限。
    • 4~5 次:大多数应用场景下足够,既能平滑网络抖动,又不会太耗时。
    • 8~10 次:对高精度要求或网络环境较差时可适当增加,但超过 10 次收益递减。
    • NTP 协议官方实现(如 ntpd)通常会持续采样并动态调整,但一次性校时时,4~8 次是常见选择。
  • 建议:
    • 一般应用:4~5 次即可。
    • 对时精度要求高或网络不稳定:8 次左右。
    • 极端高精度:可采样 10 次以上,并剔除最大/最小值后再取平均。
  • 你可以根据实际网络环境和对时精度需求灵活调整采样次数。

校时频率建议(多久同步一次)

NTP(网络时间协议)一般多久校时一次,取决于应用场景和对时精度要求。常见建议如下:

  • 桌面/服务器操作系统:
    • 通常每 64 秒 ~ 1024 秒(1~17 分钟)自动同步一次。Windows 默认每 1 小时同步一次;Linux 的 ntpd/chronyd 会根据网络状况动态调整,通常在几分钟到几十分钟之间。
  • 嵌入式/物联网设备:
    • 常见做法是每 10 分钟 ~ 1 小时同步一次。如果设备掉线或唤醒后,也建议立即同步一次。
  • 高精度场景:
    • 对时精度要求极高(如金融、工业控制),可缩短到每分钟甚至更频繁,但需注意不要对 NTP 服务器造成过大压力。
  • 低功耗/低频率场景:
    • 对时精度要求不高的设备,可以每几小时甚至每天同步一次。

实际建议:

  • 普通应用:每 10~30 分钟同步一次即可。
  • 对时精度高:每 1~5 分钟同步一次。
  • 低功耗/低频率:每小时或每天同步一次。

上下行不对称延迟对 NTP 的影响

NTP 算法假设“请求(上行)”和“响应(下行)”的网络延迟大致相等。如果上下行延迟差异很大(比如上行 10 ms,下行 100 ms),则公式计算出的 offset 会有较大误差,导致校时不准确。

实际应对:

  1. 多次采样,取最小延迟的样本:
    • 优先采用“最小网络延迟”对应的 offset 作为校时依据,因为最小时延时上下行更可能接近对称,误差更小。
  2. 剔除异常值:
    • 可剔除延迟明显偏大的样本,只用延迟较小的样本计算平均 offset。
  3. 网络环境优化:
    • 尽量保证 NTP 客户端与服务器之间的网络路径稳定、对称,减少上下行延迟差异。

常见网络场景下的上下行延迟误差参考

  1. 有线以太网(Ethernet)
    • 上下行延迟差异极小,通常在 1~5 ms 以内,网络对称性最好。
    • 绝大多数情况下可忽略不计。
  2. 局域网 Wi‑Fi(WLAN)
    • 信号好时:5~15 ms
    • 信号一般/有干扰时:10~30 ms
    • 极端拥塞/弱信号:30 ms 以上
  3. 4G/5G 蜂窝网络
    • 4G:10~30 ms(正常),30~80 ms(拥塞/弱信号),>100 ms(异常)
    • 5G:5~20 ms(正常),20~50 ms(拥塞/弱信号)
  4. 3G 蜂窝网络
    • 20~80 ms(正常),>100 ms(拥塞/弱信号)
  5. 公网/跨运营商/卫星链路
    • 公网/跨运营商:20~100 ms,偶尔更高
    • 卫星链路:100~500 ms,甚至更高,且极不对称

实际建议:

  • 以太网/优质 Wi‑Fi:上下行误差 <10 ms,NTP 校时非常可靠。
  • 蜂窝网络:<30 ms 为佳,>50 ms 建议多次采样取最优。
  • 公网/卫星:误差大时需剔除异常样本,或考虑更稳健的时钟同步策略。

许可证

本项目采用 Apache License 2.0 开源许可证,详见根目录的 LICENSE 文件。

联系方式

如有问题或建议,请联系邮箱:ligengrong@hotmail.com

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

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.250817.1009 103 8/17/2025
1.0.250816.1339 57 8/16/2025