2
in = new BufferedReader (new InputStreamReader(client.getInputStream()));
out = new DataOutputStream(client.getOutputStream());
ps = new PrintStream(out);

public void run() {
    String line;    

    try {
        while ((line = in.readLine()) != null && line.length()>0) {
            System.out.println("got header line: " + line);
        }
        ps.println("HTTP/1.0 200 OK");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ps.println("Content-type: text/html\n\n");
    ps.println("<HTML> <HEAD>hello</HEAD> </HTML>");
}

The program runs without errors and ps.println does not print anything to the browser. Any idea why?

Eli Acherkan
  • 6,401
  • 2
  • 27
  • 34
Rona
  • 25
  • 1
  • 2
  • 6

2 Answers2

2

Have you tried flushing the stream ? Without any other info I'm guessing that your PrintStream is storing up the characters but isn't actually outputting them (for efficiency's sake).

See flush() for more info.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 1
    Note also that [`PrintStream.close()`](http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#close%28%29) *"Closes the stream. This is done by **flushing** the stream and then closing the underlying output stream."* JavaDoc *quote* by Oracle, **emphasis** by me. – Andrew Thompson Jan 09 '12 at 16:28
  • public void run() { String line; try { while ((line = in.readLine()) != null && line.length()>0) { System.out.println("got header line: " + line); } out.println("HTTP/1.0 200 OK\r\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println("Content-type: text/html\r\n\r\n"); out.println(" hello "); out.println(" 22222 "); out.flush(); } – Rona Jan 09 '12 at 16:52
  • @Andrew - yes. However I didn't bring close() into the discussion since it wasn't clear to me whether the stream *should* be closed. – Brian Agnew Jan 09 '12 at 17:05
  • @BrianAgnew It would seem the thing to do after ending an output string with ` – Andrew Thompson Jan 09 '12 at 17:11
2

You have several problems. First: according to HTTP standard:

The request line and headers must all end with (that is, a carriage return followed by a line feed).

So, you need to send "\r\n" characters to terminate line.

Also, you are using println function with "\n" character. Println will also add newline character to the end of the string.

So you need to change these lines:

ps.println("HTTP/1.0 200 OK");
...
ps.println("Content-type: text/html\n\n");

to

ps.print("HTTP/1.0 200 OK\r\n")
ps.print("Content-type: text/html\r\n\r\n");

And also, dont forget to flush();

kenota
  • 5,640
  • 1
  • 15
  • 11