r3labs / sse

Server Sent Events server and client for Golang
Mozilla Public License 2.0
870 stars 180 forks source link

readme: A way to detect disconnected clients #125

Closed phomlish closed 2 years ago

phomlish commented 2 years ago
    go func() {
        // Received Browser Disconnection
        <-ctx.Done()
        println("The client is disconnected here")
        return
    }()

the golang compiler complains: undeclared name: ctx

purehyperbole commented 2 years ago

@phomlish

Sorry for not responding sooner. There was a typo in the readme which I will fix. The correct code is:

go func() {
    // Received Browser Disconnection
    <-r.Context().Done()
    println("The client is disconnected here")
    return
}()
frederikhors commented 2 years ago

I think we can close this now.

phomlish commented 2 years ago

That's working for me. Is there a way to somehow match the connection that was disconnected to one that was opened?

drewp commented 1 year ago

You could look at r.RemoteAddr at these two points:

    mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
        log.Println("client connects", r.RemoteAddr)
        go func() {
            <-r.Context().Done()
            log.Println("client disconnected", r.RemoteAddr)
        }()

        server.ServeHTTP(w, r)
    })
2022/12/01 15:09:01 client connects 127.0.0.1:52370
2022/12/01 15:09:02 client disconnected 127.0.0.1:52370
2022/12/01 15:09:02 client connects 127.0.0.1:52382
2022/12/01 15:09:03 client disconnected 127.0.0.1:52382