Ajith
Ajith

Reputation: 103

Observe the ping of socketio client at server side

I know that the socketio client sends a ping at every 25 secs (heartbeat interval) and gets a response back from the server. I want to print this ping from client on the server side and also if possible capture the ping response sent back by the node server.

I tried using

socket.on("ping", function(data) {
    console.log("received ping");
});
socket.on("pong", function(data) {
    console.log("received pong");
});

both on client and the server side but i am not able to capture them

Upvotes: 8

Views: 14677

Answers (2)

Rahul Saini
Rahul Saini

Reputation: 11

I have made it work, we just need to reverse it, i.e.

socket.conn.on('packet', (packet) => {
  if (packet.type === 'pong') console.log('sending pong');
});
socket.conn.on('packetCreate', (packet) => {
  if (packet.type === 'ping') console.log('received ping')
});

on 'packet' event we get the packet type as pong and on event packetCreate we get the packet.type as ping.

Upvotes: 1

Patrick Roberts
Patrick Roberts

Reputation: 51886

This snippet can run on the server. The documentation for the underlying engine.io server socket specifies the parameters for the event listeners packet and packetCreate, and that object is located on socket.conn:

socket.conn.on('packet', function (packet) {
  if (packet.type === 'ping') console.log('received ping');
});

socket.conn.on('packetCreate', function (packet) {
  if (packet.type === 'pong') console.log('sending pong');
});

Turns out the engine.io documentation for these events are wrong. The arguments are not type and data, it is a single argument packet that contains the properties type and data, according to the source for the packet event and the packetCreate event.

Upvotes: 12

Related Questions