tpeczek/Lib.AspNetCore.ServerSentEvents

[Question] Disconnect a client

Closed this issue · 3 comments

Hi Tomasz, I have a question. How do I disconnect a client on purpose?

This is the (untested) code I've come up with.

var res = client.GetType().GetField("_response", BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(client) as HttpResponse;
res?.HttpContext.Abort();

Obviously not an ideal approach. So I was wondering whether your library offers a better option? Maybe an API that I didn't see?

Thanks

Hi,

In general SSE doesn't provide a way to close connection from server perspective. This is why I don't expose any API for it. If you try to close connection forcibly (like above) the client will notice it and attempt to reconnect (that's how SSE works).

To achieve close functionality, you need a logic on client side to handle it. You can take a look at discussion here: #22

Actually what I'm trying to achieve is to disconnect a client when authorization is revoked. Does the library offer anything to take care of this?
I could send a ": CLOSE" to command the client to disconnect, but a malicious client may ignore it. So, for now, I'm just using reflection.

No, currently there is nothing available out of the box and it is an API very hard to get right.

Exposing HttpContext brings risk that someone will try to interact with response directly. Exposing Abort may create a false impression that it is reliable operation. I will put some more thinking into if there is something safe which can be done here.