首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何判断客户端何时使用NodeJS断开与网络套接字的连接?

如何判断客户端何时使用NodeJS断开与网络套接字的连接?
EN

Stack Overflow用户
提问于 2019-09-23 10:19:05
回答 1查看 310关注 0票数 0

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

代码语言:javascript
复制
        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函数,似乎都没有做我正在寻找的事情。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-23 10:38:56

你在你的this.wss.on('connection', function connection(ws) {...})中寻找一个ws.on("close", function close() {...})。根据您的代码:

代码语言:javascript
复制
        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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58054930

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档