usingSystem;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Collections;usingUnityEngine;usingSystem.Threading;publicclassNetworkTimeProtocolExample:MonoBehaviour{voidStart(){StartCoroutine(Request());}IEnumeratorRequest(){ThreatedJob<DateTime>tj=newThreatedJob<DateTime>(GetNetworkTime,2);yieldreturntj;Debug.Log(tj.data);}//Completely picked from http://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-cpublicstaticDateTimeGetNetworkTime(){conststringntpServer="pool.ntp.org";varntpData=newbyte[48];ntpData[0]=0x1B;varaddresses=Dns.GetHostEntry(ntpServer).AddressList;varipEndPoint=newIPEndPoint(addresses[0],123);varsocket=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);socket.ReceiveTimeout=3000;socket.Connect(ipEndPoint);socket.Send(ntpData);socket.Receive(ntpData);socket.Close();ulongintPart=(ulong)ntpData[40]<<24|(ulong)ntpData[41]<<16|(ulong)ntpData[42]<<8|(ulong)ntpData[43];ulongfractPart=(ulong)ntpData[44]<<24|(ulong)ntpData[45]<<16|(ulong)ntpData[46]<<8|(ulong)ntpData[47];varmilliseconds=(intPart*1000)+((fractPart*1000)/0x100000000L);varnetworkDateTime=(newDateTime(1900,1,1)).AddMilliseconds((long)milliseconds);returnnetworkDateTime;}}publicclassThreatedJob<T>:CustomYieldInstruction{Threadthread;floatabordTime;floatendTime;boolstarted=false;publicTdata;publicoverrideboolkeepWaiting{get{if(!started){endTime=Time.unscaledTime+abordTime;started=true;thread.Start();}boolisTimeCompleted=Time.unscaledTime>=endTime;if(isTimeCompleted){started=false;thread.Abort();returnfalse;}returnthread.IsAlive;}}publicThreatedJob(Func<T>job,floatabordTime=2){this.abordTime=abordTime;ThreadStartthre=newThreadStart(delegate{data=job.Invoke();});thread=newThread(thre);}}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.