0

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

这是我的代码:

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();
    }
}
4

1 回答 1

2

显然,服务器返回两行。reader.readLine();在之前添加String time = 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();
        }
    }
}
于 2012-10-04T13:15:16.503 回答