gpt4 book ai didi

java - 我创建了一个带有自动刷新功能的 PrintWriter;为什么它不自动冲洗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:02:55 26 4
gpt4 key购买 nike

我的客户端是一个网络浏览器,并使用这个 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, the println, printf, or format methods will flush the output buffer

它并没有说 write() 会刷新输出缓冲区。尝试改用 println(),它应该会像您期望的那样刷新。

关于java - 我创建了一个带有自动刷新功能的 PrintWriter;为什么它不自动冲洗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1240968/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com