我有一个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之前,它似乎是空的。如何检测实际关闭的连接?
更新
我还尝试了close事件和onclose函数,似乎都没有做我正在寻找的事情。
发布于 2019-09-23 10:38:56
你在你的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);https://stackoverflow.com/questions/58054930
复制相似问题