最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - websocket ping with node js - Stack Overflow

programmeradmin2浏览0评论

I am learning on how to use websockets. I am returning data to the front-end from the server via normal ws.send but I would at the same time I would like to have a set interval time to ping the front-end to see if clints are still alive there.. This is the code I am using at the moment.

ws.on('connection', function connection(ws, req) {

  ws.on('message', function ining(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);
  });
});

I want to just wait 300 seconds, if there is no response from the front-end I will terminate the websocket after the first heartbeat send by me

Here is my front-end code.

ws.onopen = function(){
    console.log("Connected");
}
ws.onclose = function(){
    console.log("Disconnected");
    ws.send('Disconnected');
}

Whats happening now is that, when I close the browser in the front-end the server in the back-end is still pinging, if I console.log it.

I am learning on how to use websockets. I am returning data to the front-end from the server via normal ws.send but I would at the same time I would like to have a set interval time to ping the front-end to see if clints are still alive there.. This is the code I am using at the moment.

ws.on('connection', function connection(ws, req) {

  ws.on('message', function ining(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);
  });
});

I want to just wait 300 seconds, if there is no response from the front-end I will terminate the websocket after the first heartbeat send by me

Here is my front-end code.

ws.onopen = function(){
    console.log("Connected");
}
ws.onclose = function(){
    console.log("Disconnected");
    ws.send('Disconnected');
}

Whats happening now is that, when I close the browser in the front-end the server in the back-end is still pinging, if I console.log it.

Share Improve this question asked Oct 15, 2017 at 13:23 Masnad NihitMasnad Nihit 1,9962 gold badges22 silver badges41 bronze badges 15
  • What do you mean by client are still alive ? – user2652134 Commented Oct 15, 2017 at 13:28
  • @BrahmaDev Client ( in the browser ) - if they close the browser they are gone, thats what I meant. – Masnad Nihit Commented Oct 15, 2017 at 13:30
  • If they close the browser, the websocket connection is gone too. You should no longer find them in ws.clients. – user2652134 Commented Oct 15, 2017 at 13:37
  • @BrahmaDev Not always, I want to use ping messages as a means to verify that the remote endpoint is still responsive. Even in the websocket repo in github they said it and I copied this example from there as well – Masnad Nihit Commented Oct 15, 2017 at 13:39
  • Can you please point me to that. This is new to me. – user2652134 Commented Oct 15, 2017 at 13:41
 |  Show 10 more ments

1 Answer 1

Reset to default 3

You have to clear the Timeout with clearInterval

Here is a working example with 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);

output is :

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,
发布评论

评论列表(0)

  1. 暂无评论