dqotv26286
2016-01-04 12:23 阅读 136

如何保持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 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
    }
    
    点赞 评论 复制链接分享
  • donglan6777 donglan6777 2016-01-07 15:11

    golang.org/x/net/websocket does not implement ping-pong from RFC 6455, but the gorilla websocket implementation does. Minimal example with Gorilla websocket

    c := time.Tick(pingInterval)
    go func(){
           for  _ := range c {
               if err := conn.WriteControl(Ping...); err != nil {
                     handle error 
                }
          }
       }()
    
              -----
    
    conn.SetPongHandler(func(string) error { return conn.SetReadDeadline(time.Now().Add(pingInterval)) })
    go func(){
          for {
               if _, _, err := conn.NextReader(); err != nil {
                    handle error
               }
           }
        }()
    
    点赞 评论 复制链接分享

相关推荐