原因
很多种业务需求,要客户端与服务端的时间同步,比如在交易状态,需要验证客户端与服务端的时间,比如集群,比如记录文件安全 、审查和监控,文件时间戳,存取安全与确认等等,总之用处多多
NTP时间服务器
NTP时间服务器:Network Time Protocol
作用:用来给其他主机提供时间同步服务,在搭建服务器集群的时候,需要保证在各个节点时间一致。
上客户端代码
public void getWebTime() {
try
{
// NTP服务端地址
const string ntpServer = "192.168.100.10";
// NTP message size - 16 bytes of the digest (RFC 2030)
byte[] ntpData = new byte[48];
// Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
IPAddress ip = IPAddress.Parse(ntpServer);
// The UDP port number assigned to NTP is 123
IPEndPoint ipEndPoint = new IPEndPoint(ip, 123);//addresses[0]
// NTP uses UDP
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
// Stops code hang if NTP is blocked
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
// 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 = swapEndian(intPart);
fractPart = swapEndian(fractPart);
ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000UL);
// UTC time
DateTime webTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(milliseconds);
string localTime = DateTime.Now.ToString("yyyyMMddHHmmss");
// Local time
DateTime dt = webTime.ToLocalTime();
SyncTime(dt);
}
catch (Exception ex)
{
AppLog.Info(LoggerEnum.LogType.OTHER.ToString(), "同步时间失败 " + ex.Message);
}
}
// 小端存储与大端存储的转换
private uint swapEndian(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
/// <summary>
/// 设置系统时间
/// </summary>
public static Boolean SyncTime(DateTime currentTime)
{
Boolean flag = false;
try
{
SystemTime sysTime = new SystemTime();
sysTime.wYear = Convert.ToUInt16(currentTime.Year);
sysTime.wMonth = Convert.ToUInt16(currentTime.Month);
sysTime.wDay = Convert.ToUInt16(currentTime.Day);
sysTime.wDayOfWeek = Convert.ToUInt16(currentTime.DayOfWeek);
sysTime.wMinute = Convert.ToUInt16(currentTime.Minute);
sysTime.wSecond = Convert.ToUInt16(currentTime.Second);
sysTime.wMiliseconds = Convert.ToUInt16(currentTime.Millisecond);
sysTime.wHour = Convert.ToUInt16(currentTime.Hour);
SetLocalTime(ref sysTime);//设置本机时间
flag = true;
}
catch (Exception)
{
flag = false;
}
return flag;
}
用的是vs2016 是不是感觉编译老是改不了本地的时间—呵呵
对了,最后设置完,这个√ 要去掉