2010-10-17 44 views
2

以下程序從時間服務器獲取時間有什麼問題。Java:套接字編程示例

public class SocketTest 
{ 
    public static void main(String[] args) 
    { 
     Socket s = new Socket(「time-A.timefreq.bldrdoc.gov」, 13); 
      BufferedReader in = new BufferedReader(
        new InputStreamReader(s.getInputStream())); 
     String line; 
     do 
     { line = in.readLine(); //read line of text from socket 
       if (line != null) System.out.println(line); 
     } 
     while(line != null); 
    } 

} 

回答

5

的引號的標誌應該是"而不是。也就是說,你應該有

Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); 

而不是

Socket s = new Socket(「time-A.timefreq.bldrdoc.gov」, 13); 

此外,你需要封裝在一個try/catch塊的IO操作,或申報拋出IOException的方法。

除此之外,我沒有太多的投訴。如果導入類不當,就會打印出類似這樣

55486 10-10-17 05:30:44 22 0 0 604.7 UTC(NIST) * 

這大約是我會怎麼寫它

import java.io.*; 
import java.net.*; 

public class SocketTest { 
    public static void main(String[] args) { 
     try { 
      Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); 
      BufferedReader in = new BufferedReader(new InputStreamReader(
        s.getInputStream())); 
      String line; 
      while ((line = in.readLine()) != null) 
       System.out.println(line); 

      s.close(); 
     } catch (IOException ioex) { 
      ioex.printStackTrace(); 
     } 
    } 
} 

把裏面的S.CLOSE()如果你是finally塊挑剔和程序是大於只是一個像這樣的測試程序。

+0

哎呀!謝謝@aioobe – rohit 2010-10-17 05:37:48

+0

s.close()應該可能在finally塊內。 – 2010-10-17 05:52:36

+0

是的,我同意。 :-) – aioobe 2010-10-17 05:55:02

2

您需要用雙引號(")包圍的字符串,看起來像你正在使用倒引號:

new Socket(「time-A.timefreq.bldrdoc.gov」, 13); 
     ^      ^