2012-02-26 39 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 
相关问题