流式传输文本数据时禁用 Chrome 缓冲

Disabling Chrome buffering when streaming text data

我们有一个通过 http 传输文本数据的网站。它的设置方式如下:

当使用普通 curl 或 FireFox 时,文本从第一个字节流式传输到浏览器。但是当使用 Chrome 时,在发送 1024 个字节之前不会显示任何文本。之后,一切都会立即显示出来。

问题:有没有办法禁用这种缓冲行为?

更多信息:这是一个简单的 ASP.NET 页面,演示了该行为:

<%@ language=c# %>

<%
    Response.BufferOutput = false;
    Response.ContentType = "text/plain";

    for (int i=0; i<50; i++)
    {
        Response.Write("01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567\r\n");
        System.Threading.Thread.Sleep(1000);
    }
%>

使用 web.config 禁用压缩:

<configuration>
    <system.webServer>
        <urlCompression doStaticCompression="false" doDynamicCompression="false"/>
    </system.webServer>
</configuration>

我在 http://bufferingtest.azurewebsites.net/ 也有一个现场重现 运行。只需从 Chrome 和 FireFox 中点击它以观察不同的行为。

尝试将 Content-Typetext/plain 切换到 application/octet-stream

检查一下,进一步阅读:

Do I need Content-Type: application/octet-stream for file download?

这个修复对我来说非常有效。我遇到了与您描述的相同的问题,发送编码为 text/plain; charset=UTF-8 的小文本块导致 Chrome 延迟,但在 Firefox 中没有。将类型更改为 application/octet 在不影响 FireFox 性能的情况下解决了 Chrome 上的问题。

X-Content-Type-Options: nosniff 添加到您的 headers,让我知道您的情况。

根据Mozilla Docs

The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should not be changed and be followed. This allows to opt-out of MIME type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.