[英]How to get real time for a game
我正在使用Java,我正在制作游戲。 在這個游戲中,實時是非常重要的一部分。 出於這個原因,我試圖使用Ntp獲得實時。
我在網上找到的是這段代碼。
import java.net.InetAddress;
import java.util.Date;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
public class test{
public static void main(String args[]) throws Exception{
String TIME_SERVER = "time-a.nist.gov";
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getReturnTime();
Date time = new Date(returnTime);
System.out.println("Time from " + TIME_SERVER + ": " + time);
}
}
我的問題是使用這個,系統仍然得到System.currentMillis(); 因為它實際上會打印出本地機器獲取時間消息的時間。 因此,如果玩家將桌面時間改為未來,游戲時間也會發生變化。
如果有人可以幫忙以獲得實時我會非常感激。 PS我沒有服務器,我的游戲將在Kongregate上播放,數據將在播放器計算機上。
提前致謝。
只需在程序開始時通過NTP獲取一次,然后使用System.nanoTime()獲取之后的相對時間。 它完全是單調的,不會通過設置系統時間來改變。
根據NTPUDPClient
javadoc:
要使用該類,只需打開一個打開的本地數據報套接字並調用
getTime()
來檢索時間。 然后調用close以正確關閉連接。 在不重新建立連接的情況下,允許連續調用getTime。
您在代碼中缺少對open()
的調用(技術上也是close()
,但這不是您的問題的原因)。
此外,在您的要求中,您聲明您需要實時(而不是本地客戶端可以設置的任何時間)。 此數量不應直接獲得,而應作為匹配本地時間與服務器(遠程)時間所需的偏移量,通過方法getOffset()
。
如果獲得實時是一個常見的過程,您可能只想在開始時使用NTP一次,並使用獲得的偏移來糾正未來的系統時間,從而減少檢索實時時的延遲。
這樣的過程可以在類中描述:
public class TimeKeeper{
// Constant: Time Server
private final String TIME_SERVER = "time-a.nist.gov";
// Last time the time offset was retrieved via NTP
private long last_offset_time = -1;
// The real time, calculated from offsets, of when the last resync happened
private long retrieve_time;
private synchronized void resync(){
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = null;
try{
timeClient.open();
timeInfo = timeClient.getTime(inetAddress);
}catch(IOException ex){
return;
}finally{
timeClient.close();
}
// Real time calculated from the offset time and the current system time.
retrieve_time = System.currentTimeMillis() + timeInfo.getOffset();
last_offset_time = System.nanoTime();
}
public long getRealTimeInMillis(){
// Possible to set some resync criteria here
if(last_offset_time == -1){
resync();
// Handle exception whilst retrieving time here
}
// Returns the system time, corrected with the offset
return retrieve_time + Math.round((System.nanoTime() - last_offset_time) / 1000.0)
}
}
試試這個:
String TIME_SERVER = "time-a.nist.gov";
TimeTCPClient client = new TimeTCPClient();
try {
client.connect(TIME_SERVER);
System.out.println(client.getDate());
} finally {
client.disconnect();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.