I'm developing chat rooms based on Twitter hashtag with Server sent events, with the package https://github.com/antage/eventsource
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.
func (sh StreamHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
es := eventsource.New(
&eventsource.Settings{
Timeout: 2 * time.Second,
CloseOnTimeout: true,
IdleTimeout: 2 * time.Second,
Gzip: true,
},
func(req *http.Request) [][]byte {
return [][]byte{
[]byte("X-Accel-Buffering: no"),
[]byte("Access-Control-Allow-Origin: *"),
}
},
)
es.ServeHTTP(resp, req)
go func() {
var id int
for {
id++
time.Sleep(1 * time.Second)
es.SendEventMessage("blabla", "message", strconv.Itoa(id))
}
}()
}
As of December 2018, apparently CloseNotifier is deprecated. The recommended solution is to use the Request
Context. The following worked for me:
done := make(chan bool)
go func() {
<-req.Context().Done()
done <- true
}()
<-done
You can use CloseNotifier which lets you know if the underlying http connection has closed. Like:
notify := w.(http.CloseNotifier).CloseNotify()
go func() {
<-notify
// connection close, do cleanup, etc.
}()
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With