我的客户端是一个网络浏览器,并使用这个 url 向我的服务器发送请求:
http://localhost
这是服务器端代码。问题出在ServingThread
类的run方法上。
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() ) ;
输出没有到达浏览器。 只有当我使用流手动刷新时,输出才会到达浏览器
out.flush() ;
我的问题: new PrintWriter( socket.getOutputStream(), true )
应该自动刷新输出缓冲区,但它并没有这样做。为什么?
最佳答案
来自Javadocs :
Parameters:
out
- An output stream
autoFlush
- A boolean; if true, theprintln
,printf
, orformat
methods will flush the output buffer
它并没有说 write()
会刷新输出缓冲区。尝试改用 println()
,它应该会像您期望的那样刷新。
关于java - 我创建了一个带有自动刷新功能的 PrintWriter;为什么它不自动冲洗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1240968/