eventsource icon indicating copy to clipboard operation
eventsource copied to clipboard

How to detect client disconnection ?

Open gperrudin opened this issue 10 years ago • 6 comments

Hello, I'm developping chat rooms based on Twitter hashtag with Server sent events. I have a problem concerning the disconnection of the client. I run a goroutine to send messages to the client, but when the client disconnects, the goroutine still runs. I don't know how to detect on the server side that the client is disconnected. You can find a part of my code here : https://gist.github.com/Guiguillermo/f214fbda9aacec1ea5d9

Thanks !

gperrudin avatar Aug 20 '15 16:08 gperrudin

You can send to client a dummy "PING" data periodically. You can't detect a disconnect without sending any data.

antage avatar Aug 20 '15 18:08 antage

Thanks for your answer. Do you know the better way to do this ? I was thinking that I could use ReponseWriter.Write() to send data but this does not automatically send data as it's buffered. I also don't know how to know if the client received the data.

gperrudin avatar Aug 20 '15 20:08 gperrudin

You can invoke conn.Read() and set ReadDeadline with a short duration before. If the connection is disconnected you get a error like "Broken pipe". If the connection is ok you get error "Timeout expired".

antage avatar Aug 20 '15 21:08 antage

The problem is that I don't see how to get the "conn" variable from my "ResponseWriter"/"Request".

gperrudin avatar Aug 20 '15 22:08 gperrudin

@Guiguillermo http://golang.org/pkg/net/http/#example_Hijacker

antage avatar Aug 21 '15 01:08 antage

The problem with Hijack() is that it takes control of the http connection, so the eventsource doesn't work anymore because it needs the http connection. I haven't found any way to give back the http connection.

gperrudin avatar Aug 21 '15 10:08 gperrudin