2012-10-04 104 views
0

我使用一些代碼從NTP(網絡時間協議)中花費時間。我嘗試了很多來自this list的服務器,但總是收到一個空字符串。我不知道這是因爲服務器錯誤,或者我的代碼有一些問題。Java Socket: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(); 
    } 
} 
+0

你說的是這個:http://en.wikipedia.org/wiki/Daytime_Protocol,對不對? – Fildor

+0

好的,我很困惑。這是_not_ NTP。這是一個不同的協議。但無論如何:你只是空字符串還是例外? – Fildor

回答

2

Aparently,服務器返回兩行。在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(); 
     } 
    } 
} 
+0

不錯!!!你怎麼能知道:D – hqt

+1

你需要讀直到'reader.readLine();'返回的字符串爲空。到那時你已經到了流的盡頭。這實際上應該在循環中完成,但上面的代碼對於此示例已足夠。 –

+0

非常感謝:) – hqt

相關問題