Example usage for org.apache.commons.net.ntp NTPUDPClient setDefaultTimeout

List of usage examples for org.apache.commons.net.ntp NTPUDPClient setDefaultTimeout

Introduction

In this page you can find the example usage for org.apache.commons.net.ntp NTPUDPClient setDefaultTimeout.

Prototype

public void setDefaultTimeout(int timeout) 

Source Link

Document

Set the default timeout in milliseconds to use when opening a socket.

Usage

From source file:org.urbancortex.routes.NTPClient.java

public static TimeInfo main(String[] args) {
    System.out.println(args);//w w  w. j av a 2  s .  c o m

    if (args.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);
    }

    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
        client.open();
        for (String arg : args) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(arg);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info);

                return info;

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

    client.close();
    return null;
}

From source file:util.android.util.DateUtils.java

public static Date getNTPTime() {
    NTPUDPClient timeClient = new NTPUDPClient();
    timeClient.setDefaultTimeout(2000);

    TimeInfo timeInfo;/*from www . j  ava2s .c  om*/
    try {
        timeClient.open();
        InetAddress inetAddress = InetAddress.getByName(getNTPServer());
        timeInfo = timeClient.getTime(inetAddress);

        long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
        Date time = new Date(returnTime);
        timeClient.close();
        return time;
    } catch (Exception e) {
        e.printStackTrace();
        return new Date();
    }
}