PrintStream doesn't print

2.7k views Asked by At
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?

2

There are 2 answers

4
Brian Agnew On

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.

4
kenota On

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();