4

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?

6
  • Have you checked the examples in the Github repo? Commented May 21, 2016 at 17:46
  • @JohnSmith This one? Commented May 21, 2016 at 17:48
  • Nope, this one. Commented May 21, 2016 at 17:51
  • @JohnSmith I'm not sure how that would help :/ could you explain? Commented May 21, 2016 at 17:56
  • It shows how to handle ping/pong requests. Basically you don't really need to do anything other than handling the deadlines as it is in the example. Once there is no response from the client within the specified timeframe, you can just return (close the connection on the server). Commented May 21, 2016 at 18:03

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.