关闭websocket连接错误

时间:2016-11-22 17:24:36

标签: node.js websocket webrtc

您好我在node.js服务器上使用websockets以便建立WebRTC连接。但是当我结束连接时,节点服务器控制台会给我以下错误:

        conn.otherName = null;
                       ^

TypeError: Cannot set property 'otherName' of undefined

其他名称是在连接中设置的另一个Peer和I的名称,如下所示:     案例"提供":             //对于前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 
           });
        } 

之后我就这样关闭了连接:

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

如何更改它以便能够在不崩溃节点服务器的情况下关闭连接?

1 个答案:

答案 0 :(得分:0)

使用一些防御性代码来阻止它破坏是非常简单的,改变这个

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(这是一个练习),但它会阻止它崩溃