Alain Roy
Alain Roy

Reputation: 165

Is there any way to stop the listening from Socket.io?

I try to stop listening in socket.io. For example, in my case, I get the data from a socket like this.

Socket.on('event', function(data) {}}

How can I stop listening in socket.io? Thanks

Upvotes: 1

Views: 3457

Answers (3)

Isravel
Isravel

Reputation: 46

The 'off' function can also be used.

  1. socket.off('news'); // stops listening to the "news" event

  2. socket.off('news', myFunction); // useful if you have multiple listeners for the same event socket.off(); // stops listening to all events

Upvotes: 2

Jeba
Jeba

Reputation: 858

To unsubscribe all listeners of an event

socket.off('event-name');

To unsubscribe a certain listener

socket.off('event-name', listener);

Or You can use following things also,

socket.removeListener(eventName, listener)
socket.removeAllListeners([eventName])

Ref: https://socket.io/docs/server-api/#socket-removeListener-eventName-listener

Upvotes: 6

ofundefined
ofundefined

Reputation: 3309

To close the connection:

socket.close() or socket.disconnect()

Returns Socket

Disconnects the socket manually.

To stop listening to some specific listener

socket.off('event', function(){})

Unbind the specified event handler (opposite of .on()).

If you decide to use this method, be careful! socket.off() does not stop the this client-side socket from receiving any server-sent messages, it just prevents the specified event handler from firing.

Actually, a socket instance inherits every method from Emitter class (https://github.com/component/emitter), so you can use .hasListeners(), .once() and already said .off() (to remove an specific event listener).

Here you find a nice doc about these and other Socket.io methods: https://sailsjs.com/documentation/reference/web-sockets/socket-client/io-socket-on

Upvotes: 4

Related Questions