2012-02-26 40 views
0

我寫了這個簡單的Java程序,它連接到內部服務器並返回域詳細信息。但是,我面臨一個奇怪的問題。我可能聽起來很愚蠢,但這裏是程序!使用緩衝讀取器和套接字

import java.io.*; 
import java.net.*; 
public class SocketTest { 
    public static void main(String[] args) { 
     String hostName; 
     int i = 0; 

     try {     
      Socket socketClient = new Socket("whois.internic.net", 43); 
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 
      InputStream in = socketClient.getInputStream(); 
      OutputStream out = socketClient.getOutputStream(); 
      System.out.println("Please Enter the Host Name!!"); 
      hostName = bf.readLine();  
      hostName = hostName + "\n"; 
      byte[] buf = hostName.getBytes(); 
      out.write(buf); 

      while((i = in.read()) != -1) { 
       System.out.print((char)i); 
      } 

      socketClient.close(); 
     } catch(UnknownHostException uht) { 
      System.out.println("Host Error"); 
     } catch(IOException ioe) { 
      System.out.println("IO Error " + ioe); 
     } catch(Exception e) { 
      System.out.println("Exception " + e); 
     } 
    } 
} 

程序運行正常,沒有任何運行時錯誤,但它沒有顯示輸出,當我嘗試從InterNIC的服務器中的最後一塊try塊的打印結果。我嘗試重新排列代碼,發現如果在創建套接字流後放置bf.readLine(),則不會有輸出。但是,如果將它放置在套接字創建之前(在main方法的開始處),程序將顯示預期的輸出。

是否有任何流衝突或左右?我是Java網絡的新手。解決方案可能很明顯,但我無法理解!請幫幫我!!!

+0

您需要正確地縮進代碼,它是不可讀的。 – skaffman 2012-02-26 18:00:05

回答

1

移動你的輸入流初始化您發送域輸出流後......這對我的作品在當地:

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

public class SocketTest { 
    public static void main(String[] args) { 
     String hostName; 
     int i = 0; 
     try { 
      Socket socketClient = new Socket("whois.internic.net", 43); 
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 

      OutputStream out = socketClient.getOutputStream(); 
      System.out.println("Please Enter the Host Name!!"); 
      hostName = bf.readLine(); 
      hostName = hostName + "\n"; 
      byte[] buf = hostName.getBytes(); 
      out.write(buf); 

      InputStream in = socketClient.getInputStream(); 
      while ((i = in.read()) != -1) { 
       System.out.print((char) i); 
      } 
      in.close(); 
      out.close(); 
      socketClient.close(); 

     } catch (UnknownHostException uht) { 
      System.out.println("Host Error"); 
     } catch (IOException ioe) { 
      System.out.println("IO Error " + ioe); 
     } catch (Exception e) { 
      System.out.println("Exception " + e); 
     } 
    } 
} 

輸出:

Please Enter the Host Name!! 
yahoo.com 

Whois Server Version 2.0 

Domain names in the .com and .net domains can now be registered 
with many different competing registrars. Go to http://www.internic.net 
for detailed information. 

YAHOO.COM.ZZZZZZZ.GET.ONE.MILLION.DOLLARS.AT.WWW.UNIMUNDI.COM 
YAHOO.COM.ZZZZZZ.MORE.INFO.AT.WWW.BEYONDWHOIS.COM 
....Whole bunch more 
相關問題