我正在编写一个简单的Java代理。总体架构是给我的(方法签名等),这是Main类的外观:
private static Socket clientSocket;
private static ServerSocket client;
private static int myPort;
public static void init(int port) throws IOException {
client = new ServerSocket(port);
clientSocket = client.accept();
}
public static void handle(Socket clientSocket) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
HttpRequest httpRequest = new HttpRequest(in);
String hostname = httpRequest.getHost();
//443 hardcoded from reading the http headers.
//Testing using isitchristmas.com
Socket serverSocket = new Socket(hostname, 443);
BufferedReader out = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
HttpResponse httpResponse = new HttpResponse(out);
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
try {
myPort = Integer.parseInt(args[0]);
try {
System.out.println("Initializing socket...");
init(myPort);
} catch (IOException e) {
System.out.println("[ERROR]: " + e.getMessage());
}
handle(clientSocket);
} catch (Exception e) {
System.out.println("[ERROR]: " + e.getMessage());
}
}
但是,在HttpResponse
类中读取时,控制台会挂起并且永远不会完成请求:
public HttpResponse(BufferedReader fromServer) throws IOException {
String line;
String statusLine = "";
// Never goes past here
while ((line = fromServer.readLine()) != null) {
if (line.isEmpty()) {
break;
}
if (line.toLowerCase().contains("status")) {
statusLine = line;
}
response.append(line);
}
if (!response.toString().isEmpty()) {
getDataAndHeadersFromResponse(response.toString());
System.out.println("\n\nHTTP Response:\n");
System.out.println("Status Line: " + statusLine);
System.out.println("Header Lines: " + headerLines + "\n\n");
System.out.println("Data: " + data);
}
}
我怀疑它与我如何创建套接字有关...不在close()
上调用ServerSocket
会发出一个已经在使用的地址:JVM_Bind异常。我似乎也没有得到serverSocket参数。正如你现在所知,我不太熟悉套接字编程。这有什么不对?
答案 0 :(得分:1)
BufferedReader
解决此问题,因为您必须计算字节数,而不是字符数。\r\n
,而不是\n
。作业缺乏:
BufferedReader
DataInputStream
从服务器读取DataInputStream
:InputStream
就足够了学生应该抱怨。