简体   繁体   中英

PrintStream doesn't print

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM