Understand Client and Server Events

Socket.IO communication is based on named events.

An event consists of an event name and optional data.

For example:

socket.emit('hello', 'John');

The client emits an event called hello with the value John.

The server receives it using:

socket.on('hello', (name) => {
  console.log(name);
});

The same concept works in the opposite direction. The server can emit events that the browser listens for.

Important methods:

MethodPurpose
socket.emit()Sends an event
socket.on()Registers an event listener
socket.once()Registers a listener that runs once
socket.off()Removes an event listener
io.emit()Sends an event to all connected clients

Use meaningful event names such as chat:send, chat:message, and user:joined instead of generic names such as event1.

Event Communication

Client to Server

socket.emit()

The browser sends an event to the server.

Server Receives

socket.on()

The server listens for events from a particular connection.

Server to Client

socket.emit()

The server sends an event to one connected client.

Client Receives

socket.on()

The browser listens for server events.

Key Takeaways
  • Socket.IO uses named events.

  • Both client and server can emit and receive events.

  • Use descriptive and consistent event names.