Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe from a socket.io subscription?

Suppose there are objects making subscriptions to a socket server like so:

socket.on('news', obj.socketEvent)

These objects have a short life span and are frequently created, generating many subscriptions. This seems like a memory leak and an error prone situation which would intuitively be prevented this way:

socket.off('news', obj.socketEvent)

before the object is deleted, but alas, there isn't an off method in the socket. Is there another method meant for this?

Edit: having found no answer I'm assigning a blank method to overwrite the wrapper method for the original event handler, an example follows.

var _blank = function(){};  var cbProxy = function(){     obj.socketEvent.apply(obj, arguments) }; var cbProxyProxy = function(){     cbProxy.apply ({}, arguments) } socket.on('news', cbProxyProxy);  // ...and to unsubscribe  cbProxy = _blank; 
like image 720
Bijou Trouvaille Avatar asked Feb 23 '12 18:02

Bijou Trouvaille


People also ask

How do I remove a Socket.IO connection?

click(function(){ socket. disconnect(); });

Is Socket.IO expensive?

Even in terms of network traffic, Socket.IO is way more expensive. In fact, with plain WebSockets, the browser may need to run just two requests: The GET request for the HTML page. The UPGRADE connection to WebSocket.

Is Socket.IO any good?

Conclusion. I think Socket.io is a very useful piece of technology and is incredibly relevant today in spite of the popular view that widespread support for WebSockets makes it redundant. I would recommend that it be used for highly interactive applications. Its namespacing in particular is its strongest point.


2 Answers

From looking at the source of socket.io.js (couldn't find it in documentation anywhere), I found these two functions:

removeListener = function(name, fn) removeAllListeners = function(name) 

I used removeAllListeners successfully in my app; you should be able to choose from these:

socket.removeListener("news", cbProxy); socket.removeAllListeners("news"); 

Also, I don't think your solution of cbProxy = _blank would actually work; that would only affect the cbProxy variable, not any actual socket.io event.

like image 126
Andrew Magee Avatar answered Sep 19 '22 10:09

Andrew Magee


If you want to create listeners that "listens" only once use socket.once('news',func). Socket.io automatically will distroy the listener after the event happened - it's called "volatile listener".

like image 22
András Endre Avatar answered Sep 20 '22 10:09

András Endre