1 extends Reference 2 3 #NTP网络对时(未做超时处理和错误处理) 4 5 const JAN_1970 = 2208988800 6 7 func i2l(int32): 8 var i2l = StreamPeerBuffer.new() 9 i2l.put_32(int32) 10 i2l.seek(0) 11 return i2l.get_64() 12 13 func ntp(): 14 var err = 0 15 var udp = PacketPeerUDP.new() 16 err = udp.set_dest_address("ntp.ntsc.ac.cn",123) 17 var packSend = StreamPeerBuffer.new() 18 packSend.put_8(27) #LI|VN|Mode 19 packSend.put_8(0) #Stratum 20 packSend.put_8(0) #Poll 21 packSend.put_8(0) #Precision 22 packSend.put_32(0) #Root Delay 23 packSend.put_32(0) #Root Dispersion 24 packSend.put_32(0) #Reference Identifier 25 packSend.big_endian = true 26 packSend.put_64(0) #Reference Timestamp 27 packSend.put_64(0) #Originate Timestamp 28 packSend.put_64(0) #Receive Timestamp 29 var clientSendTime = OS.get_unix_time()+JAN_1970 30 packSend.put_32(clientSendTime) #Transmit Timestamp 31 packSend.put_32(0) #Transmit Timestamp 32 err = udp.put_packet(packSend.data_array) 33 print("客户-发送时间",clientSendTime) 34 udp.wait() 35 var dataRecv = udp.get_packet() 36 udp.close() 37 var clientRecvTime = OS.get_unix_time()+JAN_1970 38 print("客户-接收时间",clientRecvTime) 39 var packRecv = StreamPeerBuffer.new() 40 packRecv.big_endian = true 41 packRecv.data_array = dataRecv 42 packRecv.seek(24) 43 var serverClientTime = i2l(packRecv.get_32()) 44 print("服务-客户端时间",serverClientTime) 45 packRecv.seek(32) 46 var serverRecvTime = i2l(packRecv.get_32()) 47 print("服务-接收时间",serverRecvTime) 48 packRecv.seek(40) 49 var serverSendTime = i2l(packRecv.get_32()) 50 print("服务-发送时间",serverSendTime) 51 var diff = (serverRecvTime-clientSendTime+serverSendTime-clientRecvTime)/2 52 print("补偿",diff) 53 var oldTime = OS.get_unix_time() 54 print("当前时间",oldTime) 55 var timeZone = OS.get_time_zone_info() 56 print("当前时区",timeZone) 57 var newTime = OS.get_datetime_from_unix_time(oldTime+diff+timeZone.bias*60) 58 print("校正时间",newTime)