【问题标题】:Closing websocket connection error关闭 websocket 连接错误
【发布时间】:2016-11-30 03:23:05
【问题描述】:

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

        conn.otherName = null;
                       ^

TypeError: Cannot set property 'otherName' of undefined

Other name 是另一个 Peer 的名称,我在连接中设置如下: 案例“报价”: //例如。用户A想呼叫用户B 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" 
          }); 
        }  
     } 
  } 
});

如何更改它以关闭连接而不会导致我的节点服务器崩溃?

【问题讨论】:

    标签: node.js websocket webrtc


    【解决方案1】:

    通过一些防御性代码来阻止它破坏非常简单,改变这个

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

    它没有解决为什么 users[connection.otherName] 返回未定义(这是你的练习),但它会阻止它崩溃

    【讨论】:

    • 无论如何它都会崩溃,问题是当我单击两次发送“关闭”消息的按钮时。由于它已经关闭,它返回未定义,因此它崩溃并显示相同的错误日志。
    • 我在答案中添加了另一个防御性 if 语句 - 这是您应该在整个代码中采用的策略,以防止发生此类错误。我还添加了一条评论,询问为什么当您在关闭处理程序中时,您正在尝试发送消息?尝试这样做似乎是一件坏事。
    • 成功了,谢谢!以这种方式将离开发送到另一个端点,因此呼叫结束。
    猜你喜欢
    • 2016-03-13
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2019-10-22
    • 2012-08-08
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多