I created a PrintWriter with autoflush on; why isn

2019-04-24 17:58发布

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条回答
我只想做你的唯一
2楼-- · 2019-04-24 19:04

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.

查看更多
登录 后发表回答