Home  >  Article  >  Backend Development  >  How to Keep WebSocket Connections Alive in Go?

How to Keep WebSocket Connections Alive in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 19:16:29397browse

How to Keep WebSocket Connections Alive in Go?

Maintaining WebSocket Connections in Go

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn