Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io client: how to determine if a handler is already installed

What happens if you call the 'on' method multiple times for the same function on a socket? Does calling it multiple times simply overright the last registered function or does it use more resources?

If it is the later, then how do you determine if a handler is already registered?

like image 708
SPlatten Avatar asked Dec 12 '15 10:12

SPlatten


People also ask

How do you check if socket IO client is connected or not?

You can check the socket. connected property: var socket = io. connect(); console.

How many players can Socket.IO handle?

Socket.io maxes out my CPU at around 3000 concurrent users. This is on Intel i7 CPU. Because of this I have to run multiple node/socket.io processes to handle the load. For 100 concurrent connections you should be fine.

What is the difference between Socket.IO and socket IO client?

socket-io. client is the code for the client-side implementation of socket.io. That code may be used either by a browser client or by a server process that is initiating a socket.io connection to some other server (thus playing the client-side role in a socket.io connection).

Does Socket.IO reconnect after disconnect?

Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.


2 Answers

I just looked at the socket in Firebug, there is a member called '_callbacks'.

It contains all the registered callbacks, so detecting if one is already registered is as simple as:

    if ( socket._callbacks[strHandlerName] == undefined ) {
    //Handler not present, install now
        socket.on(strHandlerName, function () { ... } );
    }

Thats it!

like image 86
SPlatten Avatar answered Oct 18 '22 16:10

SPlatten


I am used to work with it this way.

    var baseSocketOn = socket.on;

    socket.on = function() {
        var ignoreEvents = ['connect'] //maybe need it

        if (socket._callbacks !== undefined &&
            typeof socket._callbacks[arguments[0]] !== 'undefined' &&
            ignoreEvents.indexOf(arguments[0]) === -1) {
               return;
        }
        return baseSocketOn.apply(this, arguments)
    };

This is best practice

like image 27
xorxor Avatar answered Oct 18 '22 14:10

xorxor