Tomcat不会刷新响应缓冲区 [英] Tomcat does not flush the response buffer
问题描述
我在 Tomcat 7上测试了
下面,但似乎响应相反忽略了它们,而不是像预期的那样在线上刷新内容。 HttpResponse #flushBuffer
和 PrintWriter #flush
i tested HttpResponse#flushBuffer
and PrintWriter#flush
on Tomcat 7
below, but it seemed that the response rather ignored them than flushed the content over the wire asap as expected.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("say hi now");
pw.flush();
response.flushBuffer();
try {
Thread.sleep(5000);
} catch (Exception e) {
}
pw.println("say bye in 5 seconds");
}
}
显示的浏览器延迟之后,嗨和再见在一起。这是不正当行为还是打算?
The brower displayed "hi" and "bye" together after the delay. Is it a misbehavior or intended?
@EDIT
根据 @Tomasz Nurkiewicz
的建议,我再次使用 curl
进行测试,然后问题就消失了。似乎标准浏览器和 tcp / ip monitor
打包来自同一个http响应的小块内容
将它们组合在一起。
According to @Tomasz Nurkiewicz
's suggestion, i tested again with curl
then the issue was gone. It seems that standard browsers and tcp/ip monitor
pack small pieces of contents
from the same http response to render them together.
@EDIT 2
同时观察到 HttpResponse #flushBuffer
和 PrintWriter #flush
drive Tomcat 7
发送客户端分块数据。
It's also observed that both HttpResponse#flushBuffer
and PrintWriter#flush
drive Tomcat 7
to send the client chunked data.
推荐答案
<的API code> flushBuffer() 非常精确:
The API for flushBuffer()
is very precise:
强制任何要写入客户端的缓冲区中的内容。对此方法的调用会自动提交响应,这意味着将写入状态代码和标题。
Forces any content in the buffer to be written to the client. A call to this method automatically commits the response, meaning the status code and headers will be written.
因此,根据Tomcat的实现到规范(缓冲区更积极,如果它们太小则保持刷新)或客户端(浏览器)在实际渲染之前等待更多输入。
So either Tomcat is not implemented according to the spec (buffers more aggressively and holds flushes if they are too small) or the client (browser) waits for more input before actually rendering it.
Can you try with curl or nc
instead?
这篇关于Tomcat不会刷新响应缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!