It seems that using curl and most web browsers my server code is closing the connection before the client is able to read the response. Here is my code
public void run() {
try {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
System.out.println(input);
// getRequestObject(input);
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " + this.serverText + " - " + time + "").getBytes());
output.flush();
output.close();
input.close();
System.out.println("Request processed: " + time);
} catch (IOException e) {
// report exception somewhere.
e.printStackTrace();
}
}
protected String readInputStream(InputStream input) throws IOException {
String inputLine;
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuilder sb = new StringBuilder();
while (!(inputLine = in.readLine()).equals("")) {
sb.append(inputLine);
}
return sb.toString();
}
Any thoughts?
Perhaps the problem could be caused by the fact that you’re not reading the client’s data. The client is trying to send you HTTP headers, but you immediately start sending the response. Try reading from the
InputStreamuntil you receive an empty line (which signals the end of the request HTTP headers) and then start sending the output.If you need to embed an HTTP server in your application, I strongly recommend you to use an existing library. Implementing your own HTTP compliant server is going to be tedious work. See