Search code examples
javalibgdxapache-commons-net

libGDX : freezing my game when I call server host


I want to create daily bonus like other games, so I called commons-net-3.6 library from Apache to get current time from internet. Then I wrote this code:

NTPUDPClient timeClient = new NTPUDPClient();
String TIME_SERVER = "time-a.nist.gov";
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
Date time = new Date(returnTime);
System.out.println(time);

But, sometime work fine, and sometime not works and freeze my game (not responding) , WHY ??

sorry for my bad English.


Solution

  • Are you calling this code on a separate Thread?

    This must not be done on the libgdx rendering thread, which must be called at least 60 times in a second. Doing a request to a server is time-consuming and will block the thread until it is done. If the request isn't asynchronously you have to run it on a separate Thread.

    The easiest way (but not the best) is to do something like this

    new Thread() {
        public void run(){
           //Here you need to do the request
        }
    }.start();
    

    You can find more info here https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html