这是我的主要课程 - Main.java。用于控制请求者,但为了完整性而添加。
import java.io.IOException;
import HtmlRequester.Requester;
public class Main {
public static void main(String[] args) {
Requester rq = new Requester("www.google.co.za", 80);
try {
rq.htmlRequest();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Connection failed.");
System.exit(-1);
}
}
}
这是 requester.java,为简短而编辑。
package HtmlRequester;
import java.net.*;
import java.io.*;
public class Requester{
Socket httpSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String server;
int port;
public void setAttributes(String server, int port){
this.server = server;
this.port = port;
}
public String htmlRequest(String server, int port) throws IOException{
try {
httpSocket = new Socket(InetAddress.getByName(server), port);
out = new PrintWriter(httpSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
httpSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + server);
System.exit(-1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + server + "on port " + port);
System.exit(-1);
}
finally{
System.out.println("Successful connection.");
}
out.println(compileRequestText());
out.println("");
String t;
String ret = "";
System.out.println("wait...");
try {
while((t = in.readLine()) != null)
{
ret.concat(t);
System.out.println(t);
}
System.out.println("done");
}
catch(SocketException e)
{
System.err.println("Socket Exception :(");
}
System.out.println("Succesful data transfer.");
out.close();
in.close();
httpSocket.close();
return ret;
}
private String compileRequestText(){
String ret = "GET / HTTP/1.1";
return ret;
}
}
发生的情况是 Request.java 中的第二个 try-catch 块,该块包含:
while((t = in.readLine()) != null)
将执行,并成功显示来自服务器的响应。但是,在显示响应后,循环将停止执行,代码不会前进到 finally 块。在那个while循环之后程序似乎没有继续。有人知道为什么吗?
即 System.out.println("done"); 永远不会到达,不会抛出异常或编译器错误。