简体   繁体   English

关闭WebSocket连接错误

[英]Closing websocket connection error

Hello I'm using websockets on my node.js server in order to stablish WebRTC connections. 您好,我正在我的node.js服务器上使用websockets来稳定WebRTC连接。 But when I end the connection the node server console gives me the following error: 但是当我结束连接时,节点服务器控制台给我以下错误:

        conn.otherName = null;
                       ^

TypeError: Cannot set property 'otherName' of undefined

Other name is the name of the other Peer and I'ts setted up in the connection like this: case "offer": //for ex. 其他名称是其他Peer的名称,我将在连接中进行如下设置:case“ offer”:// for ex。 UserA wants to call UserB console.log("Sending offer to: ", data.name); UserA想要调用UserB console.log(“发送报价到:”,data.name);

        //if UserB exists then send him offer details 
        var conn = users[data.name]; 

        if(conn != null) { 
           //setting that UserA connected with UserB 
           connection.otherName = data.name; 

           sendTo(conn, { 
              type: "offer", 
              offer: data.offer, 
              name: connection.name 
           }); 
        } 

        break;

     case "answer": 
        console.log("Sending answer to: ", data.name); 
        //for ex. UserB answers UserA 
        var conn = users[data.name]; 

        if(conn != null) { 
           connection.otherName = data.name; 
           sendTo(conn, { 
              type: "answer", 
              answer: data.answer 
           });
        } 

Afterwards I'm closing the connection like this: 然后,我像这样关闭连接:

connection.on("close", function() { 

  if(connection.name) { 
     delete users[connection.name]; 

     if(connection.otherName) { 
        console.log("Disconnecting from ", connection.otherName); 
        var conn = users[connection.otherName]; 
        conn.otherName = null;  

        if(conn != null) { 
           sendTo(conn, { 
              type: "leave" 
          }); 
        }  
     } 
  } 
});

How can I change it to be able to close the connection without crashing my node server? 如何更改它以能够在不使节点服务器崩溃的情况下关闭连接?

Stopping it from breaking is quite simple with some defensive code, change this 使用一些防御性代码可以很容易地阻止它的中断,请更改此代码

var conn = users[connection.otherName]; 
conn.otherName = null;  

to this 对此

if (connection.otherName) {
    var conn = users[connection.otherName]; 
    if (conn) 
         conn.otherName = null;  

    if(conn != null) { 
// The connection is closed, trying to send at this point isn't a good idea
           sendTo(conn, { 
              type: "leave" 
          }); 
        }  
    }

It doesn't address why users[connection.otherName] is returning undefined (that's an exercise for you), but it will stop it crashing 它没有解决为什么users [connection.otherName]返回未定义的原因(这是您的练习),但是它将阻止崩溃

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM