我使用了一些代码来从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();
}
}
答案 0 :(得分: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();
}
}
}