0

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?

RandomUser
  • 4,140
  • 17
  • 58
  • 94
  • 1
    dunno if its related, but http headers end with `\r\n` not `\n` – goat Aug 16 '12 at 04:39
  • As @rambo already mentioned, check the introduction at wikipedia: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Response_message – home Aug 16 '12 at 04:48
  • Before closing a socket a shutdown should be issued and waited for acknowledgement. My socket programming all has been in C++ so I'm not sure how to solve it in Java but the following article might help you get a feel for the problem http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable – Eelke Aug 16 '12 at 05:12

1 Answers1

3

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 InputStream until 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

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Petr
  • 62,528
  • 13
  • 153
  • 317
  • Many thanks, I actually had a method to read the input first but I was n't actually calling it. That solved the problem, it's working great now, thanks for the tip. I also agree with you on using a library for this, but I am actually just trying to explore rather than implement – RandomUser Aug 16 '12 at 14:22