NodeJs / WS:如何抛出客户端处理的错误服务器端?

时间:2018-03-21 20:48:51

标签: node.js websocket

当我的websocket有超过2个连接时,我正在尝试抛出错误服务器端。我有这个很好的客户端onerror方法,但我无法访问我的代码部分。我正在使用nodeJS和包含错误处理文档最小的文件包ws

server.js

theWebSocketServer.on('connection', function connection(websocket){
    if (theWebSocketServer.clients.length >2) {
        // I want to throw the error here and pass it to onerror
        console.log('No access allowed', theWebSocketServer.clients.length)
    } else {
        console.log('happy connection', theWebSocketServer.clients.length)
    }
})

client.js

wsConnection.onerror = function(eventInfo) {
   alert("There was a connection error!");
   console.log("Socket error!", eventInfo);
}

如何在客户端JS上发送错误?

1 个答案:

答案 0 :(得分:0)

在文档中,我找不到任何方法将错误发送到客户端。由于ws是websockets的一个小模块,我认为它可以用来在服务器和客户端之间发送消息,如果你需要花哨的东西,你需要实现自己的协议(你解释的方式那些消息。)

例如,在这种情况下,它可能是这样的:

<强>客户端

wsConnection.onmessage = (m) => {
    // You can define errors by checking if the event data contains 
    // something specific: such as the message starts with "Error"
    // or if the property of the object is "error" and so on.
    if (m.data.startsWith("Error")) {
      alert(m.data)
      // This will show in the popup:
      // "Error: No access allowed"
    } else {
      // do something else
    }
};

wsConnection.onmessage = function(eventInfo) {
  /* Handle socket errors – e.g. internet goes down, connection is broken etc. */
}

服务器

theWebSocketServer.on('connection', function connection(websocket){
    if (theWebSocketServer.clients.length >2) {
        websocket.send("Error: No access allowed", err => {
           // Ensure your data was actually sent successfully and then
           // Close the connection
           websocket.close()

           // Just in case your data was not sent because
           // of an error, you may be interested so see what happened
           if (err) { return console.error(err); }
        })
        // I want to throw the error here and pass it to onerror
        console.log('No access allowed', theWebSocketServer.clients.length)
    } else {
        console.log('happy connection', theWebSocketServer.clients.length)
    }
})