Jerry YY Rain
Jerry YY Rain

Reputation: 4382

How to keep connection alive in GO's websocket

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 there is no any data tranfer between client and server, server will return EOF error at websocket.JSON.Receive(), it looks like a timeout mechanism.

And I have search in Google, it seems websocket protocol has a ping-pong heartbeat to maintain the connection, I want to ask whether code.google.com/p/go.net/websocket support this ping protocol or not?
What should I do if I want keep connection between client and server alive?

Upvotes: 14

Views: 21453

Answers (2)

Artem Co
Artem Co

Reputation: 143

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.Since(lastResponse) > timeout) {
            c.Close()
            return
        }
    }
  }()
}

Upvotes: 14

laslowh
laslowh

Reputation: 8594

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.

Upvotes: 4

Related Questions