How to keep connection alive in GO's websocket

前端 未结 2 1673
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 13:59

I use code.google.com/p/go.net/websocket in server, so client can get notification from server.

however, It seems after client connected to server, if the

相关标签:
2条回答
  • 2021-02-04 14:19

    Here's working drop-in solution for gorilla/websocket package.

    func keepAlive(c *websocket.Conn, timeout time.Duration) {
        lastResponse := time.Now()
        c.SetPongHandler(func(msg string) error {
           lastResponse = time.Now()
           return nil
       })
    
       go func() {
         for {
            err := c.WriteMessage(websocket.PingMessage, []byte("keepalive"))
            if err != nil {
                return 
            }   
            time.Sleep(timeout/2)
            if(time.Now().Sub(lastResponse) > timeout) {
                c.Close()
                return
            }
        }
      }()
    }
    
    0 讨论(0)
  • 2021-02-04 14:22

    As recently as 2013, the go.net websocket library does not support (automatic) keep-alive messages. You have two options:

    • Implement an "application level" keep-alive by periodically having your application send a message down the pipe (either direction should work), that is ignored by the other side.
    • Move to a different websocket library that does support keep-alives (like this one) Edit: it looks like that library has been superseded by Gorilla websockets.
    0 讨论(0)
提交回复
热议问题