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?
Reader.AServerSocketis not a 'client'. You need a new thread per accepted connection, and a loop that accepts them. Etc etc etc.ProxyCachethat doesn't cache anything but that listens for and accepts requests? An HTTP proxy that usesBufferedReader? Why aBufferedReaderto read from the client and aDataInputStreamto read from the server? Nothing mentioned about content-length? It's not even how you write a real proxy. Students should complain. There's not enough information provided here and some of the code structure is positively useless. In the meantime one of you should have a good look at the Custom Networking section of the Oracle Java Tutorial. Too broad.\r\n, not\n.