TimeTCPClient和TimeUDPClient都超时

时间:2018-10-24 12:20:15

标签: java tcp udp ntp apache-commons-net

我需要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:接收超时       在java.net.PlainDatagramSocketImpl.receive0(本机方法)       在java.net.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)       在java.net.DatagramSocket.receive(DatagramSocket.java:812)       在org.apache.commons.net.time.TimeUDPClient.getTime(TimeUDPClient.java:84)       在org.apache.commons.net.time.TimeUDPClient.getTime(TimeUDPClient.java:98)       在de.modusoft.opt.viewer.TimeSyncThread.run(TimeSyncThread.java:34)       在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;
    }

还有一个Timout异常。

  

java.net.SocketTimeoutException:连接超时       在java.net.PlainSocketImpl.socketConnect(本地方法)       在java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)       在java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)       在java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)       在java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)       在java.net.Socket.connect(Socket.java:589)       在org.apache.commons.net.SocketClient.connect(SocketClient.java:182)       在org.apache.commons.net.SocketClient.connect(SocketClient.java:203)       在org.apache.commons.net.SocketClient.connect(SocketClient.java:296)       在de.modusoft.opt.viewer.TimeSyncThread.run(TimeSyncThread.java:29)       在java.lang.Thread.run(Thread.java:748)

host是一个字符串,并尝试使用“ 0.de.pool.ntp.org”,“ ntp.xs4all.nl”。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果需要从NTP服务器获取时间,则需要使用NTP协议。 TimeUDPClientTimeTCPClient类使用时间协议,而不是NTP。