【问题标题】:Gorilla Websocket - Read error: repeated read on failed websocket connectionGorilla Websocket - 读取错误:在失败的 websocket 连接上重复读取
【发布时间】:2016-09-18 20:54:59
【问题描述】:

使用 gorilla websocket api for go,我如何知道客户端是否仍然连接?

我现在尝试的是:

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
}

但这会导致错误repeated read on failed websocket connection

我一直在研究使用ws.SetReadDeadline(t),但我不知道如何使用它,也不知道它是否是我正在寻找的东西。

我该怎么办?

【问题讨论】:

  • 你检查过 Github repo 中的例子吗?
  • @JohnSmith This one?
  • 不,this one
  • @JohnSmith 我不确定这有什么帮助:/你能解释一下吗?
  • 它展示了如何处理 ping/pong 请求。基本上,除了处理示例中的截止日期外,您实际上不需要做任何事情。一旦在指定的时间范围内客户端没有响应,您就可以返回(关闭服务器上的连接)。

标签: go websocket server gorilla


【解决方案1】:

当 websocket 连接因websocket.ErrCloseSent 以外的错误而失败时,程序会在一个紧密的循环中旋转,直到超时。

为帮助应用程序检测此编程错误,当连接失败 (view code here) 调用 read 1000 次时,websocket 包会出现紧急情况。

要解决问题,请跳出所有错误的循环:

    err := ws.ReadJSON(&msg)
    if err != nil {
        // optional: log the error
        break
    }

使用the connection's read deadline 处理超时。

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 1970-01-01
    • 2020-04-13
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    相关资源
    最近更新 更多