简体   繁体   中英

Gorilla Websocket - Read error: repeated read on failed websocket connection

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM