rpc-websockets icon indicating copy to clipboard operation
rpc-websockets copied to clipboard

Any reason emit events on namespace level will be broadcasting instead of only to subscribers like on top level

Open wwth opened this issue 1 year ago • 1 comments

This is the code for emit on the top level (not namespace) with considerations of subscribers

        // forward emitted event to subscribers
        this.on(name, (...params) =>
        {
            // flatten an object if no spreading is wanted
            if (params.length === 1 && params[0] instanceof Object)
                params = params[0]

            for (const socket_id of this.namespaces[ns].events[name].sockets)
            {
                const socket = this.namespaces[ns].clients.get(socket_id)

                if (!socket)
                    continue

                socket.send(this.dataPack.encode({
                    notification: name,
                    params
                }))
            }
        })

This emit didn't consider subscribers of the events, and will broadcast to the namespace clients regardless subscribed or not

/**
             * Emits a specified event to this namespace.
             * @inner
             * @method
             * @param {String} event - event name
             * @param {Array} params - event parameters
             * @return {Undefined}
             */
            emit(event: string, ...params: Array<string>)
            {
                const socket_ids = [ ...self.namespaces[name].clients.keys() ]

                for (let i = 0, id; id = socket_ids[i]; ++i)
                {
                    self.namespaces[name].clients.get(id).send(self.dataPack.encode({
                        notification: event,
                        params: params || []
                    }))
                }
            },

wwth avatar Dec 20 '23 06:12 wwth

Definitely shouldn't be like that. PR welcome!

mkozjak avatar Apr 18 '24 07:04 mkozjak