I created a PrintWriter with autoflush on; why isn't it autoflushing?

时光怂恿深爱的人放手 提交于 2019-12-21 04:22:09

问题


My client is a web browser, and sending request to myserver using this url: http://localhost

This is the server side code. The problem lies in the run method of the 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());
        }
    }
}

Whether I am using

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

or

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

the output is not coming to the browser. Output is coming to the browser only if I am manually flushing using stream using

out.flush() ;

My question: new PrintWriter( socket.getOutputStream(), true ) is supposed to automatically flush the output buffer, but it's not doing so. Why?


回答1:


From the Javadocs:

Parameters:

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

It does not say that write() will flush the output buffer. Try using println() instead and it should flush like you expect it to.



来源:https://stackoverflow.com/questions/1240968/i-created-a-printwriter-with-autoflush-on-why-isnt-it-autoflushing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!