socket ping pong in javascript

To implement a SocketIO ping-pong mechanism in JavaScript, first, create a SocketIO server and client as follows:

On the server-side:

index.tsx
// create a socket io server
const io = require('socket.io')(3000);

// listen to client connections
io.on('connection', (socket) => {
  console.log('New client connected');

  // listen for ping event from client
  socket.on('ping', () => {
    console.log('Received ping event from client');
  
    // emit pong event back to client
    socket.emit('pong');
  });
});
370 chars
16 lines

On the client-side:

index.tsx
// create a socket io client
const socket = io('http://localhost:3000');

// send ping event to server every 5 seconds
setInterval(() => {
  console.log('Sending ping event to server');
  socket.emit('ping');
}, 5000);

// listen for pong event from server
socket.on('pong', () => {
  console.log('Received pong event from server');
});
337 chars
14 lines

In the above code, when the client connects to the server, it sends a ping event every 5 seconds to the server. At the server-side, we listen for ping event and on receiving it, emit a pong event back to the client. At the client-side, we listen for pong event and log it to the console. This creates a continuous ping-pong mechanism between the server and client.

gistlibby LogSnag