How to save a connection in GO websocket

I use code.google.com/p/go.net/websocket on the server, so the client can receive a notification from the server.

However, it seems that after the client connects to the server, if there is no data transfer between the client and the server, the server will return an EOF error in websocket.JSON.Receive() , it will look like a timeout mechanism.

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

+7
source share
3 answers

More recently, in 2013, the go.net web library library does not support (automatic) keep-alive messages . You have two options:

  • Introduce the "application layer", maintaining the constant presence of your application, sending a message through the pipe (any direction should work), which is ignored by the other side.
  • Switch to another websocket library that supports keep-alives ( like this one ) Edit: It looks like this library has been replaced by Gorilla websites .
+3
source

The deployment solution for the gorilla / websocket package works here .

 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 } } }() } 
+4
source

Maybe this will help: https://github.com/radugheorghies/wsconn . I wrote this package to save the connection and automatically reconnect the web socket in the event of a disconnection or in the event of an error.

0
source

All Articles