dongpou7275 2018-01-18 05:27
浏览 132
已采纳

如果我不在任何地方读取消息,则不会为大猩猩/ websocket调用CloseHandler,最终我只会得到写错误

I have a websocket server using gorilla/websocket.

I have a situation where I am simply writing messages to a set of websockets. My custom CloseHandler is never called when I close the websocket on the browser side.

However, adding a goroutine that calls ReadMessage indefinitely (till some error) leads to the CloseHandler being invoked.

Here's the basic idea: In one goroutine, I run something like this:

for {
    for client := range clients {
        client.stream <- data
    }
    time.Sleep(time.Second)
}

and the other code, called in a separate goroutine, one per client:

go (func() {
    // If I call wsock.ReadMessage here, my CloseHandler works!
})()

for msg := range myclient.stream {
    if err := wsock.WriteMessage(websocket.TextMessage, msg); err != nil {
        break
    }
}

When I close the websocket on the browser side, I expect the CloseHandler to be called, however, it's never called, instead, I eventually get an error on the WriteMessage call.

  • 写回答

1条回答 默认 最新

  • douzhu7507 2018-01-18 05:53
    关注

    The close handler is called when a close message is received from the peer. The application must read the connection to receive close and other control messages.

    If the application does not read the connection or the peer does not send a close message, then the close handler will not be called.

    If your goal is to detect closed connections, then read the connection until an error as returned as shown in the documentation:

    func readLoop(c *websocket.Conn) {
        for {
            if _, _, err := c.NextReader(); err != nil {
                c.Close()
                break
            }
        }
     }
    

    The application should only set a close handler when the application must perform some action before the connection bounces the close message back to the peer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!