MatthewWid / better-sse

⬆ Dead simple, dependency-less, spec-compliant server-sent events implementation for Node, written in TypeScript.
https://matthewwid.github.io/better-sse/
MIT License
558 stars 14 forks source link

How do I initiate session disconnection from the server? #47

Closed panta82 closed 2 years ago

panta82 commented 2 years ago

I know I can listen to 'disconnected' event to handle a client going away.

But how can I kick a client from the server?

MatthewWid commented 2 years ago

To disconnect a client you can simply call res.end(). However, this will cause the client to attempt to reconnect to the server after a short timeout, so you'll need to implement an event that makes the client disconnect themselves.

As an example, add a disconnect event that makes the client close its own connection:

const source = new EventSource("/sse");

source.addEventListener("disconnect", () => {
  source.close();
});

Then from the server you can simply send that event whenever you want to disconnect them:

session.push(null, "disconnect");

Also keep in mind you can send an HTTP 204 response code to ask a client to stop reconnecting.

panta82 commented 2 years ago

Thanks for the great reply @MatthewWid I am still getting my head around EventSourcing, didn't occur to me client might try to reconnect. I'll re-architect my thing a bit given what you said.