【问题标题】:Java Socket: NTP application always return null stringJava Socket:NTP 应用程序总是返回空字符串
【发布时间】:2012-10-04 21:15:16
【问题描述】:

我使用了一些代码从 NTP(网络时间协议)获取时间。我尝试了来自this list 的许多服务器,但总是收到一个空字符串。我不知道这是因为服务器错误,还是我的代码有问题。

这是我的代码:

String machine = "utcnist2.colorado.edu";
// standart port on Computer to take time of day on normal computer
final int daytimeport = 13;

Socket socket = null;
try {
    socket = new Socket(machine, daytimeport);
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String time = reader.readLine();
    System.out.printf("%s says it is %s %n", machine, time);
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • 你说的是这个:en.wikipedia.org/wiki/Daytime_Protocol,对吧?
  • 好吧,我很困惑。这不是 NTP。这是一个不同的协议。但无论如何:你得到的只是空字符串还是异常?

标签: java sockets network-protocols


【解决方案1】:

显然,服务器返回两行。在String time = reader.readLine(); 之前添加reader.readLine(); 使其工作。

完整的代码是:

    public static void main(String[] args) {
    String machine = "utcnist2.colorado.edu";
    // standart port on Computer to take time of day on normal computer
    final int daytimeport = 13;

    Socket socket = null;
    try {
        socket = new Socket(machine, daytimeport);
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        reader.readLine();
        String time = reader.readLine();
        System.out.printf("%s says it is %s %n", machine, time);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【讨论】:

  • 您需要阅读这些行,直到reader.readLine(); 返回的字符串为空。到那时你已经到达了流的尽头。这实际上应该在一个循环中完成,但是上面的代码对于这个例子来说已经足够了。
猜你喜欢
  • 2016-12-16
  • 2019-07-25
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
相关资源
最近更新 更多