Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 428
mogli Avatar asked Aug 06 '09 19:08

mogli


People also ask

What is autoFlush in PrintWriter?

public PrintWriter(Writer out, boolean autoFlush) Creates a new PrintWriter. Parameters: out - A character-output stream autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer.

What is autoFlush in Java?

The autoFlush attribute specifies whether the buffered output should be flushed automatically when the buffer is filled, or whether an exception should be raised to indicate the buffer overflow. A value of true (default) indicates automatic buffer flushing and a value of false throws an exception.


1 Answers

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.

like image 153
Michael Myers Avatar answered Oct 23 '22 00:10

Michael Myers