gpt4 book ai didi

Java套接字: NTP application always return null string

转载 作者:行者123 更新时间:2023-12-02 07:32:25 24 4
gpt4 key购买 nike

我使用一些代码从 NTP(网络时间协议(protocol))获取时间。我已经从 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();
}
}

最佳答案

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

关于Java套接字: NTP application always return null string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12727498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com