【问题标题】:websocket connection is closing automaticallywebsocket连接正在自动关闭
【发布时间】:2020-08-10 09:31:56
【问题描述】:

我已经在 heroku 上部署了 websocket 服务器,一切正常,但如果服务器和客户端之间在一段时间后没有传输,则连接关闭。我不知道是谁在关闭连接服务器或客户端以及如何解决这个问题。

这是我的 node.js 客户端代码-

const Websocket = require('ws');

var ws = new Websocket('https://secure-mountain-02060.herokuapp.com/');

ws.onmessage = function(event){
console.log(event.data);
}

ws.onclose = function(){
console.log('server close');
}

【问题讨论】:

标签: node.js websocket


【解决方案1】:

我发现解决方案服务器由于客户端不活动而正在关闭连接。 因为我们必须在特定时间后 ping 服务器,该时间可能非常取决于服务器。

如果有人需要,我就是这样解决的。

const Websocket = require('ws');

var  ws = new Websocket('https://secure-mountain-02060.herokuapp.com/');

function noop() {}

ws.onmessage = function(event){
  console.log(event.data);
}

ws.onclose = function(){
  console.log('server close');
}

const ping = function() {
  ws.ping(noop);
}

setInterval(ping, 30000);

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2012-08-08
    • 1970-01-01
    • 2016-05-15
    相关资源
    最近更新 更多