我用autoflush创建了一个PrintWriter;为什么不自动进行? [英] I created a PrintWriter with autoflush on; why isn't it autoflushing?
问题描述
我的客户端是一个网络浏览器,并使用此网址向myserver发送请求:
http:// localhost
My client is a web browser, and sending request to myserver using this url:
http://localhost
这是服务器端代码。问题出在 ServingThread
类的run方法。
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());
}
}
}
我是否正在使用
out = new PrintWriter( socket.getOutputStream(), true ) ;
或
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() ;
我的问题: 新的PrintWriter(socket.getOutputStream(),true)
应该自动刷新输出缓冲区,但它没有这样做为什么?
My question: new PrintWriter( socket.getOutputStream(), true )
is supposed to automatically flush the output buffer, but it's not doing so. Why?
推荐答案
来自 Javadocs :
参数:
out
- 输出流
autoFlush
- 布尔值;如果为true,println
,printf
或格式
方法将刷新输出缓冲区
Parameters:
out
- An output stream
autoFlush
- A boolean; if true, theprintln
,printf
, orformat
methods will flush the output buffer
它没有说 write()
将刷新输出缓冲区。尝试使用 println()
,它应该像你期望的那样刷新。
It does not say that write()
will flush the output buffer. Try using println()
instead and it should flush like you expect it to.
这篇关于我用autoflush创建了一个PrintWriter;为什么不自动进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!