Skip to content Skip to sidebar Skip to footer

Can The Socket.io Client Emit Events Locally?

Is it possible to use socket.io to dispatch events to the client and not send them to the server? Something like: socket.emitLocally('some event', data); Here is why I'm asking:

Solution 1:

This can be done as shown on the socket.io client code on function Emitter.prototype.emit.

Events are saved on socket._callbacks with the prefix $, so for instance "connected" would be under _callbacks as "$connected".

You can replicate the behaviour of said function by using:

// You can use internal (e.g. disconnected) or custom events (e.g. ChatMessage).varevent = "MyEvent";
// Set your args exactly as in your socket.io server emit.// Note that they will be used on an apply so they must be within an array.var args = [1, 2, 3];

if(socket._callbacks) { // If the socket has callbacksvar callbacks = socket._callbacks['$' + event]; // Load the callback eventif (callbacks) {
        callbacks = callbacks.slice(0);
        for (var i = 0, len = callbacks.length; i < len; ++i)
          callbacks[i].apply(socket, args);
    } // Otherwise no calls
}

In the example above the callback for "MyEvent" will be called with the arguments 1, 2, 3.

A further example on how to use this on an actual connection:

io.on('connection', function (socket) {
    socket.on("getSingleUpdate", function(id, data){
        alert("Event #"+id+" data "+data);
    });

    functionemitLocalEvent(event/*, arg1, arg2, etc.*/) {
        if(socket._callbacks) { 
            var args = [].slice.call(arguments, 1),
                callbacks = socket._callbacks['$' + event];
            if (callbacks) {
                callbacks = callbacks.slice(0);
                for (var i = 0, len = callbacks.length; i < len; ++i)
                  callbacks[i].apply(socket, args);
            }
        }
    }

    // Emitting fake eventsemitLocalEvent("getSingleUpdate", 1, "Hello");
    emitLocalEvent("getSingleUpdate", 2, "World!");

    // You can even receive an array of events via socket.io...
    socket.on("getMultipleEvents", function(eventArray) {
        for(var i in eventArray)
            emitLocalEvent.apply(null, eventArray[i]);
    });
});

Solution 2:

Assuming you catch events on the client side using

io.on("name",callback);

you could just call

callback();

I hope i could help! =)

Post a Comment for "Can The Socket.io Client Emit Events Locally?"