dsigg21445
dsigg21445
2014-05-14 06:13
浏览 217
已采纳

如何在GO的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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dousuochu7291
    dousuochu7291 2014-05-14 19:17
    已采纳

    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.
    点赞 评论
  • dosro793520628
    dosro793520628 2017-01-05 10:16

    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
            }
        }
      }()
    }
    
    点赞 评论

相关推荐