我正在学习如何使用websockets。我通过正常的ws.send
从服务器返回数据到前端但我同时希望有一个设置的间隔时间来ping前端以查看clints是否仍然存在。这是我目前正在使用的代码。
ws.on('connection', function connection(ws, req) {
ws.on('message', function incoming(message) {
return_data = message;
heart_beat = {status:"Accepted", currentTime:"2013-02-01T20:53:32.486Z", "heartbeatInterval":300}
ws.send(JSON.stringify(heart_beat));
const interval = setInterval(function ping() {
ws.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping('', false, true);
});
}, 300);
});
});
我想等待300秒,如果前端没有响应,我会在第一次发送心跳后终止websocket
这是我的前端代码。
ws.onopen = function(){
console.log("Connected");
}
ws.onclose = function(){
console.log("Disconnected");
ws.send('Disconnected');
}
现在发生的事情是,当我在前端关闭浏览器时,后端的服务器仍在ping,如果我是console.log它。
答案 0 :(得分:1)
您必须使用 clearInterval
清除超时以下是uWebSocket的一个工作示例:
'use strict';
const uws = require('uws');
const PORT = 3000
/*********************************************************************
* Server *
*********************************************************************/
var wsServer = new uws.Server({ 'port': PORT });
let nextId=1;
wsServer.on('connection', function(ws) {
console.log('connection !');
ws.id='cnx'+nextId++;
ws.on('message', function(mess){console.log('message : '+mess); });
ws.on('error', function(error) {
console.log('Cannot start server');
});
ws.on('close', function(code, message) {
console.log('Disconnection: ' + code + ', ' + message);
clearInterval(ws.timer);
});
ws.on('pong',function(mess) { console.log(ws.id+' receive a pong : '+mess); });
ws.timer=setInterval(function(){pingpong(ws);},1000);
});
function pingpong(ws) {
console.log(ws.id+' send a ping');
ws.ping('coucou',{},true);
} // end of pingpong
/*********************************************************************
* Client *
*********************************************************************/
var wsClient1 = createClient('client1');
var wsClient2 = createClient('client2');
function createClient(id) {
var client = new uws('ws://localhost:'+PORT);
client.id=id;
client.on('ping',function(mess){ console.log(this.id+' receive a ping : '+mess); } );
client.on('message',function(mess){ console.log(this.id+' receive a message : '+mess); } );
client.on('close',function(){ console.log(this.id+' closed'); } );
return client;
}
function closeClient(client) {
console.log('close '+client.id); client.close();
}
setTimeout(function(){ closeClient(wsClient1); closeClient(wsClient2); wsServer.close(); },2500);
输出是:
connection !
connection !
cnx1 send a ping
cnx2 send a ping
client2 receive a ping : coucou
client1 receive a ping : coucou
cnx1 receive a pong : coucou
cnx2 receive a pong : coucou
cnx1 send a ping
cnx2 send a ping
client2 receive a ping : coucou
client1 receive a ping : coucou
cnx1 receive a pong : coucou
cnx2 receive a pong : coucou
close client1
close client2
client1 closed
client2 closed
Disconnection: 0,
Disconnection: 0,