简体   繁体   English

PrintStream不打印

[英]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. 该程序运行无错误,并且ps.println不会在浏览器中打印任何内容。 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). 没有任何其他信息,我猜测您的PrintStream正在存储字符,但实际上并未输出它们(出于效率考虑)。

See flush() for more info. 有关更多信息,请参见flush()

You have several problems. 你有几个问题。 First: according to HTTP standard: 第一:根据HTTP标准:

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. 因此,您需要发送“ \\ r \\ n”字符来终止行。

Also, you are using println function with "\\n" character. 另外,您正在使用带有“ \\ n”字符的println函数。 Println will also add newline character to the end of the string. Println还将在字符串末尾添加换行符。

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(); 而且,别忘了flush();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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