如何判断客户端何时使用 NodeJS 与 Web 套接字断开连接?



我有一个Node websocket,我正在尝试检测客户端何时断开连接。我根据文档尝试了以下代码,但仍然无法检测到关闭...

const wss = new WebSocket.Server({
server: this.server
});
this.wss = wss;
this.wss.on('connection', function connection(ws) {
Logger.log("verbose", `Web socket is now alive`);
ws.isAlive = true;
ws.on("pong", function(){
Logger.log("verbose", `Web socket pong`);
console.log(`the pong is ${this.isAlive} ${ws.isAlive}`);
this.isAlive = true;
});
});
setInterval(()=>{
console.log(`Setting the interval ${wss.clients.length}`);
wss.clients.forEach(function each(ws) {
if (ws.isAlive === false){
Logger.log("verbose", `The web socket died`);
return ws.terminate();
}
ws.isAlive = false;
ws.ping(()=>{});
});
}, 30000);

但是,似乎 wss.clients 在被检测到之前是空的。如何检测连接实际关闭?

更新

还尝试了关闭事件和关闭功能似乎都没有做我想要的。

您正在寻找this.wss.on('connection', function connection(ws) {...})内部的ws.on("close", function close() {...})。根据您的代码:

const wss = new WebSocket.Server({
server: this.server
});
this.wss = wss;
this.wss.on('connection', function connection(ws) {
Logger.log("verbose", `Web socket is now alive`);
ws.isAlive = true;
ws.on("pong", function(){
Logger.log("verbose", `Web socket pong`);
console.log(`the pong is ${this.isAlive} ${ws.isAlive}`);
this.isAlive = true;
});
ws.on("close", function() {
//do closing stuff here
});
});
setInterval(()=>{
console.log(`Setting the interval ${wss.clients.length}`);
wss.clients.forEach(function each(ws) {
if (ws.isAlive === false){
Logger.log("verbose", `The web socket died`);
return ws.terminate();
}
ws.isAlive = false;
ws.ping(()=>{});
});
}, 30000);

最新更新