michaelangeloio / ts-sse

utilities for Server Sent Events
MIT License
73 stars 2 forks source link

QnA: What if the connection is closed by the client? #86

Open iyxan23 opened 4 months ago

iyxan23 commented 4 months ago

Hi! Thank you for this awesome project.

I'd just like to ask a question: how can we know if the connection is closed by the client? I have a requirement where I need to notify other clients that have connected to the event stream at the time when a client sends a request to an endpoint.

So, let's say there's an endpoint of /api/broadcast, and a client made a request to it. The message should be broadcasted into clients that have connected to /api/stream.

The simplest implementation is to have a list of listeners that adds a new anonymous function when a client connected to /api/stream. That anonymous function will then have the Writer object and be able to send messages like writer.update(...). When a /api/broadcast is requested, it shall loop over the listeners and call them one-by-one, effectively sending the message across the subscribers of /api/stream.

But what if a client closes a connection to /api/stream? How can the server know to remove the listener from the list? It's getting kinda confusing. In next, the function just returns a Response and kind of forgets about it, how can we know anything about the connection?

Thanks a bunch!