当我的 websocket 有超过 2 个连接时,我试图在服务器端抛出错误。我有这个不错的客户端onerror
方法,但我无法到达我的代码的那部分。我正在使用 nodeJS 和包ws
其中有关于错误处理的最小文档。
服务器.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)
}
})
客户端.js
wsConnection.onerror = function(eventInfo) {
alert("There was a connection error!");
console.log("Socket error!", eventInfo);
}
如何发送错误以供客户端 JS 处理?
在文档中,我找不到任何发送方式给客户端一个错误. Since ws
是一个用于 websockets 的小模块,我认为它可以用于在服务器和客户端之间发送消息,如果你需要奇特的东西,你需要实现你自己的协议(你如何解释那些消息)。
例如,在本例中,它可能是这样的:
Client
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.onerror = function(eventInfo) {
/* Handle socket errors – e.g. internet goes down, connection is broken etc. */
}
Server:
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)
}
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)