In a WebSocket server built using code.google.com/p/go.net/websocket, clients can receive notifications from the server. However, client-server connections may terminate prematurely due to a timeout mechanism triggered by prolonged inactivity.
To address this issue, the WebSocket protocol includes a "ping-pong" heartbeat mechanism. This mechanism allows both the client and server to send keep-alive messages to each other, preventing the connection from being dropped.
Unfortunately, the code.google.com/p/go.net/websocket package does not natively support this ping-pong protocol. As a workaround, one can implement a custom ping-pong handler like the following:
import ( "time" "github.com/gorilla/websocket" ) 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 } } }() }
By embedding this handler in your WebSocket server, you can send periodic ping messages to the client and receive pong responses in return. This ensures that the connection remains active even during periods of inactivity.
The above is the detailed content of How to Keep WebSocket Connections Alive in Go?. For more information, please follow other related articles on the PHP Chinese website!