Home >Backend Development >Golang >How to Keep WebSocket Connections Alive with Go.net/websocket?
WebSocket connections require periodic data exchange to remain active. As part of the WebSocket protocol, a ping-pong mechanism is used to maintain the connection heartbeat. This ensures that both the client and the server are consistently sending and receiving data, preventing the connection from timing out.
Code.google.com/p/go.net/websocket does not natively support the ping-pong protocol. Therefore, it is necessary to implement a custom solution to keep the connection alive.
A simple and effective solution is to periodically send ping messages to the client from the server. These ping messages will trigger a pong response from the client, indicating that the connection is alive. If a pong response is not received within a specified timeout period, the server can close the connection.
Here is a drop-in solution for implementing this mechanism using code.google.com/p/go.net/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 implementing this solution, you can maintain active WebSocket connections even in the absence of regular data exchange.
The above is the detailed content of How to Keep WebSocket Connections Alive with Go.net/websocket?. For more information, please follow other related articles on the PHP Chinese website!