dqotv26286 2016-01-04 12:23
浏览 160

如何保持golang.org/x/net/websocket打开?

I'm naively use _, err := ws.Read(msg) to keep a Web socket open in my code. I don't think it works reliably.

In other code I've noticed people doing a sleep loop. What's the correct way to keep a Web socket open & stable? I assume the underlying library does ping/pongs?

Update: I'm pretty confident that the client.go is to blame since it doesn't seem to redial after a disconnect is seen on the server. I made a video demonstrating the issue.

  • 写回答

2条回答 默认 最新

  • dstbp22002 2016-01-04 12:56
    关注

    I misread your original question.

    No you're doing it the right away. You basically need to block the handler from returning to keep the websocket connection alive. If you don't care about the message, just discard it and do nothing with it.

    A common way people do it is to have a dedicated Read and Write goroutine, something like:

    func fishHandler(ws *websocket.Conn) {
        id := ws.RemoteAddr().String() + "-" + ws.Request().RemoteAddr + "-" + ws.Request().UserAgent()
        sockets[id] = ws
    
        go writePump(ws)
        readPump(ws)
    }
    
    func readPump(ws *websocket.Conn) {
        defer ws.Close()
        msg := make([]byte, 512)
        _, err := ws.Read(msg)
        if err != nil {
            return
        }
    }
    
    func writePump(ws *websocket.Conn) {
        // Hand the write messages here
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler