How to keep connection alive in GO's websocket

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
        }
    }
  }()
}

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.

Tags:

Go

Websocket