关闭websocket连接错误

关闭websocket连接错误

问题描述:

你好我正在我的node.js服务器上使用websockets来建立WebRTC连接。但是,当我结束连接的节点服务器控制台给了我以下错误:关闭websocket连接错误

 conn.otherName = null; 
        ^

TypeError: Cannot set property 'otherName' of undefined 

其他名称是其他同行和I'ts在这样的连接设置好的了名字: 情况下,“优惠”: // for ex。 UserA想要调用UserB console.log(“发送offer:”,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 
      }); 
     } 

后来我关闭这样的连接:

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" 
      }); 
     } 
    } 
    } 
}); 

我怎样才能改变它能够关闭不崩溃我的节点服务器的连接?

破裂停止它与一些防御性的代码很简单,改变这种

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

这个

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" 
      }); 
     } 
    } 

为什么用户[connection.otherName]被返回undefined它不涉及(这是对你的锻炼),但它会阻止它崩溃

+0

即使这样,仍然无法正常工作:/ –

+0

你的意思是不工作? – Mikkel

+0

无论如何,它会崩溃,问题是,当我点击两次发送“关闭”消息的按钮。由于它已经关闭,它返回undefined,所以它崩溃显示相同的错误日志。 –