I created a PrintWriter with autoflush on; why isn

2019-04-24 18:03发布

问题:

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.