我创建了一个带有自动刷新功能的 PrintWriter;为什么不自动冲洗?
-
12-09-2019 - |
题
我的客户端是一个网络浏览器,并使用以下网址向我的服务器发送请求:http://localhost
这是服务器端代码。问题出在run方法上 ServingThread
班级。
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 )
应该自动刷新输出缓冲区,但它没有这样做。为什么?
解决方案
来自 Java文档:
参数:
out
- 输出流
autoFlush
- 布尔值;如果为真,则println
,printf
, , 或者format
方法将刷新输出缓冲区
它并没有这么说 write()
将刷新输出缓冲区。尝试使用 println()
相反,它应该像您期望的那样冲洗。
不隶属于 StackOverflow