【发布时间】:2016-04-21 16:41:23
【问题描述】:
在 JavaScript 类中,一个 XMLHttpRequest 连接到服务器。 服务器正在缓慢地发送数据。这在 Chromium 中运行良好,但 Firefox 在随机时间(约 4 秒到约 70 秒之间)后关闭连接。
为什么 Firefox 会关闭连接?以及如何避免这种情况?
简化的JS代码:
var options = {};
options['header']=
{ 'Cache-Control':'no-cache, max-age=0',
'Content-type': 'application/octet-stream',
'Content-Disposition': 'inline'
};
// Get request information
this.http = new XMLHttpRequest();
this.http.onreadystatechange = _streamingResponse.bind(this);
this.http.open('post', url, true);
for (var i in options['header'])
{
this.http.setRequestHeader(i, options['header'][i]);
}
this.http.send('');
对于 PHP 部分,类似于:
sleep(200); //wait long time, so firefox close the socket.
如果服务器每隔几秒 (
连接关闭: - 就绪状态 = 4 - 状态 = 0
服务器似乎是正确的,因为在 Chromium 中它可以正常工作。
完整的测试代码:
test.html
<html>
<header>
</header>
<body>
</body>
<script type="application/javascript">
function log( msg )
{
document.body.appendChild(document.createElement('div').appendChild(document.createTextNode(msg)));
document.body.appendChild(document.createElement('br'));
}
function request(url)
{
function _streamingResponse()
{
if (4==this.http.readyState)
{
log('Done: ' + this.http.status);
}
else if (3==this.http.readyState)
{
var text = this.http.response.substr(this.lastRequestPos);
this.lastRequestPos = this.http.response.length;
log('Update: ' + text);
}
}
var options = {};
options['header']=
{ 'Cache-Control':'no-cache, max-age=0',
'Content-type': 'application/octet-stream',
'Content-Disposition': 'inline'
};
this.lastRequestPos=0;
// Get request information
this.http = new XMLHttpRequest();
this.http.onreadystatechange = _streamingResponse.bind(this);
this.http.open('post', url, true);
for (var i in options['header'])
{
this.http.setRequestHeader(i, options['header'][i]);
}
this.http.send('');
log('Request sent!');
}
req = new request('./test.php');
</script>
</html>
test.php
<?php
$timer = 60;
ignore_user_abort(true);
set_time_limit(0);
// Turn off output buffering and compression
ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);
ini_set('implicit_flush', true);
ob_implicit_flush(true);
while (ob_get_level() > 0) {
$level = ob_get_level();
ob_end_clean();
if (ob_get_level() == $level) break;
}
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', '1');
apache_setenv('dont-vary', '1');
}
// Set header for streaming
header('Content-type: application/octet-stream');
flush();
// Send information
sleep($timer);
echo '<yes></yes>';
flush();
?>
附加说明:Firefox 43.0.03、Chromium 47.0.2526
已编辑:
为超时设置回调它不会触发。我断定这不是超时。
this.http.timeout = 2000;
this.http.ontimeout = _streamingTimeout.bind(this);
【问题讨论】:
-
让我知道是否缺少任何信息或者我可以改进问题。
-
我正在创建一个完整的示例来简化您的测试。
-
当然可能与firefox超时有关,但我中间没有代理。此外,超时似乎要短得多(不到 2 分钟)。
-
@VishalRajole:我做了一些测试,它不是超时,因为它不会触发超时设置回调:stackoverflow.com/questions/1523686/timeout-xmlhttprequest
标签: javascript http firefox xmlhttprequest