在结束前重新加载时,JS WebRTC 在计时器中发送数据时崩溃

Sending data in a timer by JS WebRTC crashes when reloading before the end

我在节点提供的 server.js javascript 文件中有这段简单的代码:

function multiStep(myConnection, data) {
    var i=0;
        var myTimer=setInterval(function() {
        if (i<data.length){
            var element=JSON.stringify(data[i]);
            console.log("mando elemento: "+element);
            myConnection.send(element);
            i++;
        }
    }, 3000);
}

//require our websocket library 
clearInterval(myTimer);
var WebSocketServer = require('ws').Server; 
//creating a websocket server at port 9090 
var wss = new WebSocketServer({port: 9090}); 

//when a user connects to our sever 
wss.on('connection', function(connection) {

    loadJSON(function(response) { 

//when server gets a message from a connected user 
        connection.on('message', function(message){ 
                console.log("Got message from a user:", message); 
        });
        var json = JSON.parse(response);
        multiStep(connection, json, 0);
    })
});

loadJSON 只是从另一个网站加载一个 json 数据文件。 当我第一次 运行 客户端应用程序或超时结束时,一切正常。但是,如果我在超时未完成时重新加载页面,当我尝试使用服务器上旧页面的连接并报告时,我会崩溃:

/var/www/html/MATERIALI/phonegap/node_modules/ws/lib/WebSocket.js:219 else throw new Error('not opened'); ^ Error: not opened at WebSocket.send (/var/www/html/MATERIALI/phonegap/node_modules/ws/lib/WebSocket.js:219:16) at null. (/var/www/html/MATERIALI/phonegap/WebRTC/server.js:36:9) at wrapper [as _onTimeout] (timers.js:261:14) at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

事实上,鉴于页面已重新加载,我可以简单地忽略旧会话。在这些情况下如何避免服务器崩溃?

你需要一路做一些检查。您的代码假定一切都是 100%。

var json = JSON.parse(response);
multiStep(connection, json, 0);
  1. 您假设响应中有数据(它可能为空,或包含 non-json 数据)
  2. 在将 json 传递给 multiStep
  3. 之前,您还应该检查它是否是一个有效的数组
  4. 函数 multiStep 还假定 data.length 将 return 一些数值

这可能不是完整的答案,但它应该能让您开始使代码更健壮。

它可能在 myConnection.send(element); 处失败了,但这可能只是您在整个过程中缺乏检查的症状(您还可以在向其发送内容之前检查 myConnection 是否仍然有效)

参考https://developer.mozilla.org/en-US/docs/Web/API/WebSocket,你应该可以检查myConnection.readyState值:

就绪状态常量

readyState 属性使用这些常量来描述 WebSocket 连接的状态。

Constant    Value   Description
CONNECTING  0   The connection is not yet open.
OPEN    1   The connection is open and ready to communicate.
CLOSING 2   The connection is in the process of closing.
CLOSED  3   The connection is closed or couldn't be opened.

您的代码现在将如下所示:

    console.log("mando elemento: "+element);
    if (myConnection.readyState === 1)
            myConnection.send(element);
    else 
            console.log("web socket not open");

好的,我想我找到了解决方案;函数 multiStep 变为:

function multiStep(myConnection, data) {
     var i=0;
     clearInterval(myTimer);
     myTimer=setInterval(function() {
          if (i<data.length){
               var element=JSON.stringify(data[i]);
               console.log("mando elemento: "+element);
               try {
                    myConnection.send(element);
                    console.log("mandato elemento");
               } catch(err) {
                    console.log('Websocket error: %s', err);
          }
          i++;
       } else {
       }
    }, 3000);
}

而且它不再崩溃了。