我需要开发一个从 NTP 服务器获取当前时间的应用程序,但我在 Windows 8 Store App 中找不到任何示例。如果我尝试使用普通的 C# 类,它就不起作用。有谁知道如何解决这个问题?
问问题
5539 次
3 回答
2
我强烈建议避免从 HTML 页面中解析字符串 - 轻微的视图格式更改会破坏您的应用程序。
根据此答案中提供的示例,这是获取正确对象的DatagramSocket改编:DateTime
DatagramSocket socket = new DatagramSocket();
socket.MessageReceived += socket_MessageReceived;
await socket.ConnectAsync(new HostName("time.windows.com"), "123");
using (DataWriter writer = new DataWriter(socket.OutputStream))
{
byte[] container = new byte[48];
container[0] = 0x1B;
writer.WriteBytes(container);
await writer.StoreAsync();
}
收到消息后,您可以通过内置阅读器处理传入的字节数组:
void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
using (DataReader reader = args.GetDataReader())
{
byte[] b = new byte[48];
reader.ReadBytes(b);
DateTime time = GetNetworkTime(b);
}
}
GetNetworkTime
与我提到的示例几乎相同,缓冲区作为参数之一传递:
public static DateTime GetNetworkTime(byte[] rawData)
{
//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(rawData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
// stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
于 2013-05-05T20:21:08.990 回答
1
我想这就是你想要的。
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
private async Task<DateTime?> GetNistTime()
{
DateTime? dateTime = null;
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://nist.time.gov/timezone.cgi?UTC/s/0"));
HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
string text = await httpResponseMessage.Content.ReadAsStringAsync();
if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
{
string html = await httpResponseMessage.Content.ReadAsStringAsync();
string time = Regex.Match(html, @">\d+:\d+:\d+<").Value; //HH:mm:ss format
string date = Regex.Match(html, @">\w+,\s\w+\s\d+,\s\d+<").Value; //dddd, MMMM dd, yyyy
dateTime = DateTime.Parse((date + " " + time).Replace(">", "").Replace("<", ""));
}
return dateTime;
}
于 2013-04-10T10:59:44.850 回答
0
您需要一个StreamSocket ,然后自己实现 NTP 协议。如果您有用于经典 Windows 的现有 NTP C# 类,则可以调整代码以改用StreamSocket。
于 2013-04-11T08:16:50.383 回答