我使用一些代码从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();
    }
}

最佳答案

显然,服务器返回两行。在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();
        }
    }
}

关于java - Java套接字:NTP应用程序始终返回空字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12727498/

10-12 20:11