Search in sources :

Example 6 with TimeInfo

use of org.apache.commons.net.ntp.TimeInfo in project nuls by nuls-io.

the class TimeService method getWebTime.

/**
 * 获取网络时间
 * todo 可优化为哪个地址延迟小使用哪个
 *
 * @return long
 */
private long getWebTime(String address) {
    try {
        NTPUDPClient client = new NTPUDPClient();
        client.open();
        client.setDefaultTimeout(1000);
        client.setSoTimeout(1000);
        InetAddress inetAddress = InetAddress.getByName(address);
        // Log.debug("start ask time....");
        TimeInfo timeInfo = client.getTime(inetAddress);
        // Log.debug("done!");
        return timeInfo.getMessage().getTransmitTimeStamp().getTime();
    } catch (Exception e) {
        return 0L;
    }
}
Also used : NTPUDPClient(org.apache.commons.net.ntp.NTPUDPClient) TimeInfo(org.apache.commons.net.ntp.TimeInfo) InetAddress(java.net.InetAddress)

Aggregations

InetAddress (java.net.InetAddress)6 NTPUDPClient (org.apache.commons.net.ntp.NTPUDPClient)6 TimeInfo (org.apache.commons.net.ntp.TimeInfo)6 IOException (java.io.IOException)4 Date (java.util.Date)3 UnknownHostException (java.net.UnknownHostException)2