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?
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.
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.
From the Javadocs:
Parameters:
out
- An output streamautoFlush
- A boolean; if true, theprintln
,printf
, orformat
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With