On this page
Listening to events
There are several ways to handle events that are transmitted between the server and the client.
EventEmitter methods
On the server-side, the Socket instance extends the Node.js EventEmitter class.
On the client-side, the Socket instance uses the event emitter provided by the component-emitter library, which exposes a subset of the EventEmitter methods.
socket.on(eventName, listener)
Adds the listener function to the end of the listeners array for the event named eventName.
|
socket.once(eventName, listener)
Adds a one-time listener function for the event named eventName
|
socket.off(eventName, listener)
Removes the specified listener from the listener array for the event named eventName.
|
socket.removeAllListeners([eventName])
Removes all listeners, or those of the specified eventName.
|
Catch-all listeners
Since Socket.IO v3, a new API inspired from the EventEmitter2 library allows to declare catch-all listeners.
This feature is available on both the client and the server.
socket.onAny(listener)
Adds a listener that will be fired when any event is emitted.
|
socket.prependAny(listener)
Adds a listener that will be fired when any event is emitted. The listener is added to the beginning of the listeners array.
|
socket.offAny([listener])
Removes all catch-all listeners, or the given listener.
|
Validation
The validation of the event arguments is out of the scope of the Socket.IO library.
There are many packages in the JS ecosystem which cover this use case, among them:
Example with joi and acknowledgements:
|
Error handling
There is currently no built-in error handling in the Socket.IO library, which means you must catch any error that could be thrown in a listener.
|
On the server-side, using EventEmitter.captureRejections = true
(experimental, see here) might be interesting too, depending on your use case.
|
© 2014–2021 Automattic
Licensed under the MIT License.
https://socket.io/docs/v3/listening-to-events