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:
| Method | Purpose |
|---|---|
| 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
socket.emit()
The browser sends an event to the server.
socket.on()
The server listens for events from a particular connection.
socket.emit()
The server sends an event to one connected client.
socket.on()
The browser listens for server events.
Socket.IO uses named events.
Both client and server can emit and receive events.
Use descriptive and consistent event names.