java - 我创建了一个带有自动刷新功能的 PrintWriter;为什么它不自动冲洗?

标签 java io flush printwriter

我的客户端是一个网络浏览器,并使用这个 url 向我的服务器发送请求: http://localhost

这是服务器端代码。问题出在ServingThread类的run方法上。

class ServingThread implements Runnable{
    private Socket socket ;

    public ServingThread(Socket socket){
        this.socket = socket ;
        System.out.println("Receives a new browser request from "
                      + socket + "\n\n");
    }

    public void run() {
        PrintWriter out = null ;

        try {
            String str = "" ;
            out = new PrintWriter( socket.getOutputStream() ) ;
            out.write("This a web-page.") ;
            // :-(
            out.flush() ;
            // :-(
            socket.close() ;
            System.out.println("Request successfully fulfilled.") ;
        } catch (IOException io) {
            System.out.println(io.getMessage());
        }
    }
}

我是否在使用

out = new PrintWriter( socket.getOutputStream(), true ) ;

out = new PrintWriter( socket.getOutputStream() ) ;

输出没有到达浏览器。 只有当我使用流手动刷新时,输出才会到达浏览器

out.flush() ;

我的问题: new PrintWriter( socket.getOutputStream(), true ) 应该自动刷新输出缓冲区,但它并没有这样做。为什么?

最佳答案

来自Javadocs :

Parameters:

out - An output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer

它并没有说 write() 会刷新输出缓冲区。尝试改用 println(),它应该会像您期望的那样刷新。

关于java - 我创建了一个带有自动刷新功能的 PrintWriter;为什么它不自动冲洗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1240968/

相关文章:

java - 无法启动代理

java - Spring MVC 自定义作用域 bean

c# - UWP 写入 CSV 文件

c++ - 将句子作为用户的字符串输入读取

php - 如何在 PHP 中设置定时器?

java - @在HSQL数据库中生成

java - 在kony中链接JavaConnector时发生ClascastException

c++ - 相当于c++中的printf

c++ - 尝试使用 cout 打印 vector 中包含的对象列表,但排序错误

php - 提早刷新 HTML 文档 - 使用 ini_set( 'zlib.output_compression' ,'ON')?