From 63ca426544c3c40ad9adab4b06ffdf6a0a964a9c Mon Sep 17 00:00:00 2001 From: GaoLiHai <1019933576@qq.com> Date: Sat, 30 Jan 2021 19:05:07 +0800 Subject: [PATCH 1/2] Fix websocket loss of connection --- .gitignore | 4 +++- index.js | 17 +++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 7564269..19c3001 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,6 @@ test/ jsdoc* docs/ -.idea \ No newline at end of file +.idea + +.vscode \ No newline at end of file diff --git a/index.js b/index.js index 8dc9387..90cb095 100644 --- a/index.js +++ b/index.js @@ -901,9 +901,22 @@ class NodeMirai { if (this.enableWebsocket) { this.onSignal('verified', () => { const wsHost = `${this.host.replace('http', 'ws')}/all?sessionKey=${this.sessionKey}`; - (new WebSocket(wsHost)).on('message', message => { + const ws = new WebSocket(wsHost); + ws.on('message', message => { this.emitEventListener(JSON.parse(message)); - }) + }); + ws.on('open',() => { + const interval = setInterval(() => { + ws.ping((err) => { + if (err) { + // todo sth. + } + }); + }, 60000); + ws.on('close',(code, reason) => { + clearInterval(interval); + }); + }); }); } else setInterval(async () => { From 4e96c40590e01aac1c4e7305b474319b7fd20b1b Mon Sep 17 00:00:00 2001 From: queuecat <2356583659@qq.com> Date: Sat, 30 Jan 2021 19:50:44 +0800 Subject: [PATCH 2/2] Add new comment --- index.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/index.js b/index.js index 90cb095..a21d4a8 100644 --- a/index.js +++ b/index.js @@ -901,11 +901,14 @@ class NodeMirai { if (this.enableWebsocket) { this.onSignal('verified', () => { const wsHost = `${this.host.replace('http', 'ws')}/all?sessionKey=${this.sessionKey}`; + // 拿到 ws 实例,后边还要发 ping 包 const ws = new WebSocket(wsHost); + // 分发消息 ws.on('message', message => { this.emitEventListener(JSON.parse(message)); }); ws.on('open',() => { + // 建立连接后,每分钟向服务端发个 ping 包 const interval = setInterval(() => { ws.ping((err) => { if (err) { @@ -914,6 +917,7 @@ class NodeMirai { }); }, 60000); ws.on('close',(code, reason) => { + // 连接关闭后,移除定时器 clearInterval(interval); }); });