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.

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

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助