Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 36 ยท Connections and Events

Emitting and Listening to Events

Master Socket.IO events. Learn emit and on, multiple arguments, once, off, onAny, reserved event names, what survives serialization, and how to structure handlers cleanly.

Events are the heart of Socket.IO. Everything you build, from a chat message to a game move, is an event with a name and some data. The API is intentionally tiny, but a few details decide whether your handlers are predictable: how many arguments you can send, what happens to the data on the way, which names are off-limits, and how to remove listeners.

emit and on

socket.emit(eventName, ...args) sends an event; socket.on(eventName, handler) receives it. This works the same in both directions: server to client and client to server.

JavaScript
// server
socket.emit('score', 'ana', 120);

// client
socket.on('score', (player, points) => {
  console.log(player, points); // "ana" 120
});

You can pass any number of arguments, each of any JSON-friendly type: strings, numbers, booleans, null, arrays, plain objects, and also binary values like Buffer, ArrayBuffer and typed arrays. The receiving handler gets them as separate parameters, in order.

An event has no return value. emit returns immediately and tells you nothing about delivery. If you need a reply, pass a callback as the last argument (an acknowledgement); see the later chapter on reliability.

The four listener methods

Socket.IO sockets extend an event emitter, so the familiar methods exist:

  • socket.on(name, fn) runs fn every time.
  • socket.once(name, fn) runs it only the first time.
  • socket.off(name, fn) removes one listener; socket.off(name) removes all listeners of that name.
  • socket.onAny(fn) receives every event with its name first; socket.offAny(fn) removes it. There is also prependAny and the outgoing counterpart onAnyOutgoing.

onAny is a great debugging tool, because a single logger shows all traffic. The example below sets one on each side.

Node.js on, once, off and onAny

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second hello is still seen by onAny, but the once handler is gone. After remove-noise, the last noise triggers only the logger.

Reserved event names

Some names belong to Socket.IO itself, and emitting them yourself throws an error:

  • Server socket: connect, connect_error, disconnect, disconnecting, newListener, removeListener.
  • Client socket: connect, connect_error, disconnect.

Pick your own names freely otherwise. Good conventions: lower-case, descriptive, and consistent. Many teams use noun:verb (message:send, room:join) or kebab-case; avoid generic names such as data or update that hide meaning.

Define your event names in one shared constants module (or, with TypeScript, a typed event map, covered later) so a typo like 'mesage' is caught at once instead of silently never firing.

What happens to your data

Arguments are serialized before they cross the wire, so the receiver gets a copy, not the same object. Rules of thumb:

  • Plain objects, arrays, strings, numbers, booleans, null survive.
  • Date becomes an ISO string. Convert it back with new Date(value) on the other side.
  • undefined inside an object disappears; inside an array it becomes null.
  • Map, Set, class instances and functions do not survive (they become {}, or are lost). Convert them to arrays or plain objects first. Functions are only allowed as the last argument, where they mean an acknowledgement callback.
  • BigInt cannot be serialized; send a string.
  • Circular references throw an error.
  • Binary data is detected and sent as separate binary frames.

You can reproduce the JSON part of this in plain Node to see exactly what a receiver would get:

Node.js What survives serialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Treat every event argument as untrusted input too: the data came from the network, so validate its shape and size before using it. The authentication chapter returns to that.

Handler structure that scales

Registering everything inline in the connection callback works for a demo but turns into a 500-line function. A cleaner pattern splits handlers by feature and registers them per socket:

JavaScript
// chatHandlers.js
export function registerChatHandlers(io, socket) {
  socket.on('message:send', (text) => {
    io.emit('message:new', { from: socket.data.name, text });
  });
  socket.on('typing:start', () => socket.broadcast.emit('typing', socket.data.name));
}

// server.js
io.on('connection', (socket) => {
  registerChatHandlers(io, socket);
  registerGameHandlers(io, socket);
});

Each module receives io (for global broadcasts) and socket (for this client), so it can be tested on its own. This mirrors the way Express routers split routes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does socket.once('hello', fn) do?

    once registers a one-shot listener that removes itself after running.
  2. 2. Which value is NOT safely transmitted as an event argument without conversion?

    Maps are not JSON-serializable; send an array of entries or a plain object instead. Buffers are supported as binary.
  3. 3. You want one function that logs every event a socket receives. Which method?

    onAny listeners get the event name first and then its arguments. There is no wildcard string.
  4. 4. What happens to a Date sent as an event argument?

    JSON serialization turns a Date into an ISO 8601 string; convert it back on the receiving side.

Summary

  • emit sends an event with any number of arguments; on receives it; neither returns a value.
  • once, off, onAny and offAny manage and observe listeners.
  • Do not emit reserved names such as connect or disconnect.
  • Data is copied through JSON: Dates become strings, Maps and Sets are lost, BigInt fails.
  • Split handlers into modules that take (io, socket) to keep the connection callback small.

Next: Broadcasting to Many Clients