使用缓冲读卡器和套接字

时间:2012-02-26 17:49:17

标签: java sockets

我编写了这个简单的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);
        }
    }
}

程序运行正常,没有任何运行时错误,但是当我尝试在最后一块try块中从内部服务器打印结果时,它没有显示输出。我尝试重新排列代码,发现如果在创建套接字流后放置bf.readLine(),则没有输出。但是,如果我在创建套接字之前(在main方法的开头)放置它,程序将显示预期的输出。

是否有任何流冲突?我是Java的网络新手。解决方案可能很明显,但我无法理解!请帮帮我!!!

1 个答案:

答案 0 :(得分: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