Reputation: 6872
Using the gorilla websocket api for go, how do i know if a client is still connected?
What Im trying with now is:
func Listen(ws *websocket.Conn) {
connTimeout := 3
timeLastSent := time.Now().Second()
for ((timeLastSent + connTimeout) % 60) != time.Now().Second() {
msg := Message{}
err := ws.ReadJSON(&msg)
if err == websocket.ErrCloseSent {
break
} else if err != nil {
continue
}
//Message recived
EventMessage <- msg
timeLastSent = time.Now().Second()
}
//Connection timed out.
return
}
But this results in the error repeated read on failed websocket connection
.
Ive been looking into using ws.SetReadDeadline(t)
, but Ive no idea of either how to use it nor if its even the thing Im looking for.
How should i go about this?
Upvotes: 3
Views: 6888
Reputation: 120951
When the websocket connection fails with an error other than websocket.ErrCloseSent
, the program spins in a tight loop until the timeout.
To help applications detect this programming error, the websocket package panics when read is called 1000 times on a failed connection (view code here).
To fix the problem, break out of the loop on all errors:
err := ws.ReadJSON(&msg)
if err != nil {
// optional: log the error
break
}
Use the connection's read deadline to handle timeouts.
Upvotes: 4