Create a Node.js Socket.IO Test Client

Create test-client.js in the project root.

The script will:

  1. Connect to the Socket.IO server.
  2. Listen for connection events.
  3. Emit a test message.
  4. Listen for the broadcast message.
  5. Disconnect after receiving the message.
test-client.js
import { io } from 'socket.io-client';

const socket = io('http://localhost:3000');

socket.on('connect', () => {
  console.log('Connected:', socket.id);

  socket.emit('chat:send', {
    username: 'TestUser',
    message: 'Hello from Node.js test client'
  });
});

socket.on('chat:message', (message) => {
  console.log('Received:', message);
  socket.disconnect();
});

socket.on('connect_error', (error) => {
  console.error('Connection failed:', error.message);
});

Creates a standalone Socket.IO client that sends a test message and disconnects after receiving the broadcast.

Key Takeaways
  • Socket.IO clients can run outside browsers.

  • Node.js clients are useful for automated testing.

  • The same event protocol works between browser and Node.js clients.