EvilJordan
EvilJordan

Reputation: 665

Why is my socket.emit event firing multiple times (based on # of global connections) to the same client?

Below is my code for dealing with dynamically assigned namespaces. The client connects, then, using it's referrer, the client's account ID is looked up, and in a function not present below, if that account ID does not already have a namespace assigned to it, a new namespace is generated (UUID) or the existing namespace is returned.

Then, that namespace is emitted to the client, which responds in turn with a new connect message on that particular namespace.

This all works.

Unfortunately, the ns_socket.emit('hi'); statement gets fired back to the ns_socket for however many clients have connected.

To be clear, if client 1 connects to the namespace, the hi is fired once to that client. When client 2 connects to the same namespace, hi is fired twice to that second client for an unknown (to me) reason, when it should only fire once.

Any help would, obviously, be very much appreciated.

var main = io.of('').on('connection', function(socket) {
    socket.on('joinDynNs',function(data) {
        var nameslug = socket.handshake.headers.referer.match(/(http(s)?:\/\/)([A-Za-z0-9-]+)\./)[3];
        getActID(nameslug, function(actID) {
            var ns = getNamespace(nS, actID);
            socket.emit('assignNamespace',{ns:ns});
            io.of('/' + ns).on('connection', function(ns_socket) {
                ns_socket.emit('hi');
            });
        });
    });
});

Upvotes: 2

Views: 4898

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159105

Your logic is written such that a connection handler for the namespace is created whenever a socket connects to the base namespace. Thus, every time a new client connects to the base namespace, you set up another connection handler. Put another way, you're calling

io.of('/' + ns).on('connection', function(ns_socket) {
    ns_socket.emit('hi');
});

every time a new connection comes in. The connection handler is not specific to the socket you're dealing with; it fires for any new connection on the namespace. This is why you're seeing the incrementing message counts.

I'm not sure about your needs in full, but I would think that rooms would be a better solution for you; namespaces are really designed to be used for multiplexing connections (for example, multiple completely unrelated apps running on the same Socket.IO port); rooms allow you to group sockets into logical groups, and send messages to the sockets in that group.

Upvotes: 3

Related Questions