SOLVED:Java Hangs when writing response to socket
I'm writing a small server application, it just reads a browser request, prints it and returns a response. The problem is when I try to write to the output stream it hangs. No exception, no unusual exit codes, it just gets stuck on the write instruction(doesn't reach flush).
Here's my script:
Code:
import java.io.*;
import java.net.*;
public class TestSocket{
public static void main(String[] args) throws IOException{
while(true){
// Listen for client connection
ServerSocket server = new ServerSocket(9999);
Socket client = server.accept();
System.out.println("Done");
// Get the IO Streams
BufferedReader clientIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter clientOut = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String str;
// Counter for logging purposes
int cnt = 0;
// Read HTTP Request
while((str=clientIn.readLine())!=null){
System.out.print(cnt);
System.out.println(str);
cnt++;
}
System.out.println(cnt);
// Write response, script hangs here
clientOut.append("HTTP/1.0 200 OK\nDate: Sun, 04 Nov 2012 16:52:19 GMT\nContent-Type: text/html;\nConnection: keep-alive\n<html><body><h5>It worked</h5></body></html>");
clientOut.flush();
cnt++;
// Clean up
clientIn.close();
clientOut.flush();
clientOut.close();
client.close();
}
}
}
Any help greatly appreciated.
Re: Java Hangs when writing response to socket
Solved it, the problem isn't with write, it's with read. The line separator is never read, so it keeps waiting for it.
I solved the problem by replacing readLine() in the while loop by read(), so I'm reading the response character by character instead of line by line.
Code:
import java.io.*;
import java.net.*;
public class TestSocket{
public static void main(String[] args) throws IOException{
ServerSocket server = new ServerSocket(9998);
while(true){
// Listen for client connection
Socket client = server.accept();
System.out.println("Done");
// Get the IO Streams
BufferedReader clientIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter clientOut = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
char c;
// Counter for logging purposes
// Read HTTP Request CHARACTER BY CHARACTER instead of line by line
while((c=(char)clientIn.read())!=0 && c !='\n'){
System.out.print(c);
}
// Write response, script hangs here
clientOut.append("HTTP/1.0 200 OK\nDate: Sun, 04 Nov 2012 16:52:19 GMT\nContent-Type: text/html;\nConnection: keep-alive\n<html><body><h5>It worked</h5></body></html>");
clientOut.flush();
// Clean up
clientIn.close();
clientOut.flush();
clientOut.close();
client.close();
}
}
}