I am coding a simple Java proxy. The general architecture was given to me (method signatures etc), and this is how the Main class looks:
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());
}
}
However the console hangs and never completes a request when reading in HttpResponse
class:
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);
}
}
I suspect it has something to do with how I am creating the sockets... not calling close()
on ServerSocket
gives off a Address already in use: JVM_Bind exception. I also don't seem to get the serverSocket parameters right. As you can tell by now I'm not very versed in socket programming. What is wrong here?
BufferedReader
, as you have to count bytes, not chars. \\r\\n
, not \\n
. The assignment is deficient in:
BufferedReader
DataInputStream
for reading from the server DataInputStream
at all: InputStream
would suffice Students should complain.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.