#include "NET_Client.h" #ifdef WIN32 #include "jd_time.h" #endif #include "millitimer.h" #ifdef WIN32 //#include #else #include #include #endif extern unsigned long Millitimer_Adjust; long Millitimer_NetError=0; long Millitimer_Required_Tolerance = 1000; /*************************************************************************** S E T M I L L I T I M E R T O L E R A N C E ***************************************************************************/ void setMillitimerTolerance(long tol) { Millitimer_Required_Tolerance=tol; } /*************************************************************************** S Y N C M I L L I T I M E R W I T H N E T W O R K ***************************************************************************/ bool syncMillitimerWithNetwork(char *hostname, int port) { // Loop until we get a sufficiently small Net_error Millitimer_NetError=Millitimer_Required_Tolerance+1; while (Millitimer_NetError>Millitimer_Required_Tolerance) { // Connect with net master NET_Client cli; cli.blocking(); if (cli.connect(hostname,port)== -1) { puts ("ERROR opening network millitimer"); return false; } // Reset millitimerAdjust Millitimer_Adjust=0; // Get current time long starttime = Get_Milliseconds(); // Send packet starttime=htonl(starttime); cli.writeNetMsg(&starttime, 4); starttime=ntohl(starttime); // Recieve response packet long nettime; cli.readNetMsg(&nettime,4); nettime=ntohl(nettime); long endtime = Get_Milliseconds(); // Calc network adjustment and error long localtime = starttime+(endtime-starttime)/2; Millitimer_Adjust = nettime - localtime; Millitimer_NetError = (endtime-starttime)/2 +1; // Print times printf ("Start - net - end - adjust %d %d %d %d\n",starttime,nettime,endtime,Millitimer_Adjust); } return true; } /*************************************************************************** C H E C K N E T W O R K M I L L I T I M E R ***************************************************************************/ long checkNetworkMillitimer(char *hostname, int port) { // Connect with net master NET_Client cli; cli.blocking(); if (cli.connect(hostname,port)== -1) { puts ("ERROR opening check network millitimer"); return -1; } // Send packet long starttime=Get_Milliseconds(); starttime=htonl(starttime); cli.writeNetMsg(&starttime, 4); // Recieve response packet long nettime; cli.blocking(); int nbytes=cli.readNetMsg(&nettime,4); nettime=ntohl(nettime); //if (nbytes<0) { // nettime=0; //} return nettime; } /*************************************************************************** G E T M I L L I T I M E R N E T W O R K E R R O R ***************************************************************************/ long getMillitimerNetworkError() { return Millitimer_NetError; } /*************************************************************************** G E T M I L L I T I M E R A D J U S T ***************************************************************************/ long getMillitimerAdjust() { return Millitimer_Adjust; }