views:

444

answers:

1

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?

+2  A: 

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.

Michael Myers
I tried as u suggested and it's working. So, only println is considered to flush, and write, print does not. It's not mentioned in the docs, that which methods are compatible with auto-flushing and which are not. So, how do one came to know this. :)
rits
It *is* mentioned in the docs, just not for the individual methods.
Michael Myers
but there are so many overloaded methods of write, print, printf and println. How 1 came to know that which 1 is compatible with autoflusing, or only the methods ending with ln supports autoflushing.
rits
I just looked at the Javadocs. I didn't know until I saw it while researching your question.
Michael Myers
This is very well said by someone :- "Practice makes a man perfect." Anyways, thnx mmyers for your help. Cheers :-)
rits