razshare / sveltekit-sse

Server Sent Events with SvelteKit
https://www.npmjs.com/package/sveltekit-sse
MIT License
274 stars 9 forks source link

Question: Publishing data to multiple clients #13

Closed haukened closed 10 months ago

haukened commented 10 months ago

So i'm playing around with this today, and i'm looking to "broadcast" information to all connected clients.

currently my implementation is a FIFO queue with a depth of 20.:

export function GET() {
    return event(async emit => {
        // eslint-disable-next-line no-constant-condition
        while (true) {
            for (const data of Generator()) {
                if (data === undefined) {
                    await delay(100);
                    continue;
                } else {
                    emit(JSON.stringify(data));
                }
            }
        }
    }).toResponse();
}

What I'm observing is that each connected client gets some unique subset of data from that queue. I'm guessing thats because each request drains the queue of one item, which goes to one client? Is there a paradigm in this that would broadcast the same real-time data to each client once connected?

razshare commented 10 months ago

Hello @haukened , I'm not sure about your specific use case, but I would implement multiple clients like this https://github.com/tncrazvan/sveltekit-sse-issue-13

If you want to create some FIFO queue, I would suggest you use a linked list.

As for the repository above, the most important parts I would say are these 3

image

result Peek 2023-11-02 03-32

Is this the type of thing you're looking for?

haukened commented 10 months ago

Yes! I came up with a solution sort of like that, albeit not as elegant. I think I'll refactor mine to look more like this. I was using an Array instead of a Map, which makes deleting harder, and since they're both iterable and order doesn't matter, I think this will be a better solution long term.

I also didn't have the pruning on cancel, which I can see if definitely required if you want it to work for any amount of time.

Thank you for the thoughtful and detailed response!

unknownsoldier08 commented 6 months ago

Hi @tncrazvan,

Sorry to revive an old thread, but I am just trying to work through emitting to multiple clients with your example https://github.com/tncrazvan/sveltekit-sse-issue-13

However, I don't seem to be able to import the EmitterOfManyEvents type into a typescript file

image

I am guessing things may have changed since then, as I am not able to find this type in the events.d.ts

Would you have any advice on how to do the same today in typescript?

razshare commented 6 months ago

Hi @unknownsoldier08 , It's been some time since this issue so a few things changed.

Specifically I opted from hiding most internal types.

I don't think there's any harm in exposing EmitterOfManyEvents, so I just released a new version that does just that. You wil need to update to the latest version 0.8.12.

image