Firefox for Socket.io上的"websocket在页面加载时被中断"

Ama*_*mar 49 websocket socket.io

Error: The connection to <websocket> was interrupted while the page was loading.
Source File: localhost/socket.io/node_modules/socket.io-client/dist/socket.io.js
Line: 2371
Run Code Online (Sandbox Code Playgroud)

我是socket.io的新手,我试图搜索这个,但我没有得到答案.

当我在Firefox上刷新页面时,Websocket被中断.这就是服务器端等待授权客户端的原因.

这是代码:

server.js-->
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    //alert(JSON.stringify(data));  
    console.log(data);
  });

});
Run Code Online (Sandbox Code Playgroud)

的index.html

<script src="node_modules/socket.io-client/dist/socket.io.js"></script>
    <script>

      var socket = io.connect('http://localhost:8080');

      socket.on('news', function (data) {
        alert(JSON.stringify(data));
        console.log(data);
        socket.emit('my next event', { my: 'data' });
      });

    </script>
Run Code Online (Sandbox Code Playgroud)

小智 47

它发生的原因是,你没有关闭你的开放websocket.

此代码将删除此错误:

$(window).on('beforeunload', function(){
    socket.close();
});
Run Code Online (Sandbox Code Playgroud)

  • 实际上,我不认为这解决了它.我也试过[这个](http://stackoverflow.com/a/14699817/1747491),但我也没有修复它. (3认同)
  • 这对我来说没有解决问题.Firefox <48中的[bug](https://bugzilla.mozilla.org/show_bug.cgi?id=712329)是个问题,像这样的解决方法在我的Firefox版本(41)上不起作用.升级做到了; 但不幸的是,如果您正在编写一个webapp(我猜这是我们大多数人对socket.io感兴趣的原因),那么您无法确定用户使用的Firefox(或其他浏览器)的版本.:( (3认同)
  • 没有为我修复,直到我发现服务器没有响应 WebSocket“关闭”消息。现在服务器很好地确认了关闭,Firefox (60.0) 很高兴。 (2认同)
  • 2020 年我仍然遇到这个问题,但仅限于 wss:// (2认同)

use*_*062 13

这似乎是Firefox中的一个漏洞(截至2015-03-29):

https://bugzilla.mozilla.org/show_bug.cgi?id=712329

正如亚历山大指出的那样,解决方法(现在)是在beforeunload上调用websocket上的close().

更新2016-04:根据Bugzilla的说法,这将在Firefox 48中修复

  • 此解决方法不适用于socket.io(使用最新版本1.3.5) (4认同)

leg*_*ter 1

这对您的申请有什么影响?我的猜测是,在控制台中看到错误并不好。

这里的问题是,您看到 Firefox 登录时出现此错误,但您对此无能为力。无法使用try...catch块或通过websocket.onerror/捕获此错误websocket.onclose

请参阅:如何捕获 WebSocket 连接中断?

有关的: