Java Ntp Client

Java HTTP client getting time from NTP server

TCP (and UDP) port 37, which you are connecting to, is used for the TIME protocol (RFC 868). In this protocol, times are sent as a single binary 32bit integer in network byte order.

UDP port 123 is used for the NTP protocol (RFCs 1059, 1119, 1305, 5905). In this protocol, times are sent as a series of binary messages.

You can't read either type of data as text with BufferedReader.ReadLine().

NTP for TCP/IP(server-client)

System.currentTimeMillis() provides the system time

Every Socket returned by server.accept() is a separate object and your server can communicate independently with each client through each Socket object. However, since your application is time-sensitive, I would recommend using a separate thread for each client.

A simple server would be:

ServerSocket serverSock = new ServerSocket(2000);

while (true)
{
Socket fpSock = serverSock.accept();
MyThread t = new MyThread(fpSock, this);
t.start();
}

The processing you need will be done in the MyThread run() method. "this" is passed to the thread to provide a reference where each thread can callback to methods in the main class. Make sure to make such methods synchronized.

You also don't necessarily need to send the server's time to the client, simply send a generic packet which the client is expected to echo back. Use the server's timestamp for all transactions to avoid variation in client system time.

TimeTCPClient and TimeUDPClient both timing out

If you need the time from an NTP server, you need to use the NTP protocol. The TimeUDPClient and TimeTCPClient classes use the Time Protocol, not NTP.

How to get time in nanoseconds from external webservice in Java?

The Network Time Protocol (NTP) allow to sync clocks of computer systems. You can connect to any NTP server to request the current time

NTPUDPClient in package apache commons provides an NTP client

usage

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;

public long getRemoteNTPTime() {
NTPUDPClient client = new NTPUDPClient();
// We want to timeout if a response takes longer than 5 seconds
client.setDefaultTimeout(5000);
//NTP server list
for (String host : hosts) {

try {
InetAddress hostAddr = InetAddress.getByName(host);
TimeInfo info = client.getTime(hostAddr);
return info.getMessage().getTransmitTimeStamp().getTime();

}
catch (IOException e) {
e.printStackTrace();
}
}

client.close();

return null;

}

Configure several hosts to avoid if one is down. Look for servers near your hosting to reduce network latency. For example

ntp02.oal.ul.pt 
ntp04.oal.ul.pt
ntp.xs4all.nl


Related Topics



Leave a reply



Submit