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

2023-11-25

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

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

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

or

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

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

out.flush() ;

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


来自Javadocs:

参数:

out- 输出流
autoFlush- 布尔值;如果为真,则println, printf, or format方法将刷新输出缓冲区

它并没有这么说write()将刷新输出缓冲区。尝试使用println()相反,它应该像您期望的那样冲洗。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我创建了一个带有自动刷新功能的 PrintWriter;为什么不自动冲洗? 的相关文章

随机推荐