[英]Using Buffered reader and Socket
我编写了这个简单的Java程序,该程序连接到Internic服务器并返回域详细信息。 但是,我面临一个奇怪的问题。 我听起来可能很蠢,但这是程序!
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块中尝试从Internic服务器打印结果时,它没有显示任何输出。 我尝试重新排列代码,发现如果在创建套接字流后放置bf.readLine()
,则没有输出。 但是,如果将其放置在套接字创建之前(在main方法的开始处),程序将显示预期的输出。
是否存在流冲突? 我是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));
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.