Prompt Title: 生成唯一时间戳

Created 1 year ago
Votes 0
Views 102 times
0

Prompt Detail:

以下是一个实现监控本地时间是否修改并同步网络时间的示例代码:

csharp
using System; using System.Net; using System.Runtime.InteropServices; using System.Threading; namespace TimeSyncExample { class Program { static void Main(string[] args) { // 创建一个事件触发器 TimeChangedEventTrigger eventTrigger = new TimeChangedEventTrigger(); // 注册事件处理程序 eventTrigger.TimeChanged += EventTrigger_TimeChanged; // 启动事件触发器 eventTrigger.Start(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); } private static void EventTrigger_TimeChanged(object sender, EventArgs e) { Console.WriteLine("System time has been changed, syncing network time..."); try { // 获取网络时间 DateTime networkTime = GetNetworkTime(); // 设置系统时间 SetSystemTime(networkTime); Console.WriteLine("Network time has been synced successfully."); } catch (Exception ex) { Console.WriteLine($"Failed to sync network time: {ex.Message}"); } } private static DateTime GetNetworkTime() { const string ntpServer = "pool.ntp.org"; // NTP message size - 16 bytes of the digest (RFC 2030) byte[] ntpData = new byte[48]; //Connect to the server (UDP) using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { socket.ReceiveTimeout = 3000; socket.SendTimeout = 3000; socket.Connect(IPAddress.Parse(ntpServer), 123); //Set protocol version ntpData[0] = 0x1B; //Send Request socket.Send(ntpData); //Receive Time socket.Receive(ntpData); //Offset to get to the "Transmit Timestamp" field (time at which the reply //departed the server for the client, in 64-bit timestamp format." const byte serverReplyTime = 40; //Get the seconds part ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime); //Get the seconds fraction ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4); //Convert From big-endian to little-endian intPart = SwapEndianness(intPart); fractPart = SwapEndianness(fractPart); //Calculate the milliseconds part ulong milliseconds = (fractPart * 1000) / 0x100000000L; //Create a new DateTime object DateTime networkDateTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc); networkDateTime = networkDateTime.AddSeconds(intPart); networkDateTime = networkDateTime.AddMilliseconds(milliseconds); return networkDateTime; } } private static void SetSystemTime(DateTime dateTime) { SYSTEMTIME st = new SYSTEMTIME(); st.wYear = (ushort)dateTime.Year; st.wMonth = (ushort)dateTime.Month; st.wDay = (ushort)dateTime.Day; st.wHour = (ushort)dateTime.Hour; st.wMinute = (ushort)dateTime.Minute; st.wSecond = (ushort)dateTime.Second; st.wMilliseconds = (ushort)dateTime.Millisecond; SetSystemTime(ref st); } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetSystemTime(ref SYSTEMTIME st); [DllImport("
avatar
cc
Shared 5 prompts
Created 1 year ago

Leave a Comment

Related Tag Prompts

0
0
w
1 year ago 2023-05-05 00:54:36 ff