Initialize the Socket.IO Client

Create public/app.js.

The Socket.IO browser client is available through the global io function because we loaded the Socket.IO client script in index.html.

Initialize the connection using:

const socket = io();

Because the browser page and Socket.IO server use the same origin, the client automatically connects to the current host.

Socket.IO automatically attempts to establish a connection and can reconnect after temporary disconnections.

public/app.js
const socket = io();

const statusElement = document.getElementById('connection-status');

socket.on('connect', () => {
  statusElement.textContent = 'Connected';
  console.log('Connected to server:', socket.id);
});

socket.on('disconnect', (reason) => {
  statusElement.textContent = 'Disconnected';
  console.log('Disconnected:', reason);
});

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

Creates a Socket.IO client and registers handlers for successful connections, disconnections, and connection errors.

Key Takeaways
  • The io() function initializes the Socket.IO client.

  • The connect event indicates a successful connection.

  • The disconnect event indicates that the connection has closed.

  • The connect_error event helps diagnose connection failures.