TimeTCPClient 和 TimeUDPClient 都超时

TimeTCPClient and TimeUDPClient both timing out

我需要来自 NTP 服务器的时间。

我绑定了这个:

  TimeUDPClient client = new TimeUDPClient();
  try {
        client.open();
        client.setSoTimeout(10000);
        client.getTime(InetAddress.getByName(host));
        client.close();
  } catch (IOException exp) {
        System.out.println("NTP connection error");
        exp.printStackTrace();
        return;
  }

10 秒后我得到这个异常:

java.net.SocketTimeoutException: Receive timed out at java.net.PlainDatagramSocketImpl.receive0(Native Method) at java.net.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143) at java.net.DatagramSocket.receive(DatagramSocket.java:812) at org.apache.commons.net.time.TimeUDPClient.getTime(TimeUDPClient.java:84) at org.apache.commons.net.time.TimeUDPClient.getTime(TimeUDPClient.java:98) at de.modusoft.opt.viewer.TimeSyncThread.run(TimeSyncThread.java:34) at java.lang.Thread.run(Thread.java:748)

我也试过这个:

    TimeTCPClient client = new TimeTCPClient();
    client.setConnectTimeout(10000);
    try {
        client.connect(host);
        Date ntpDate = client.getDate();
        client.disconnect();
        System.out.println("ntpDate = " + ntpDate);
    } catch (IOException exp) {
        System.out.println("NTP connection error");
        exp.printStackTrace();
        return;
    }

并且还遇到了超时异常。

java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at org.apache.commons.net.SocketClient.connect(SocketClient.java:182) at org.apache.commons.net.SocketClient.connect(SocketClient.java:203) at org.apache.commons.net.SocketClient.connect(SocketClient.java:296) at de.modusoft.opt.viewer.TimeSyncThread.run(TimeSyncThread.java:29) at java.lang.Thread.run(Thread.java:748)

host 是一个字符串和一个试过的“0.de.pool.ntp.org”,"ntp.xs4all.nl"。

感谢您的帮助。

如果您需要来自 NTP 服务器的时间,则需要使用 NTP 协议。 TimeUDPClientTimeTCPClient 类 使用时间协议,而不是 NTP。