SoFunction
Updated on 2025-04-08

Implementation of socket heartbeat detection in GoLang

Heartbeat detection is a mechanism to ensure stability between the server and the client. The specific implementation method is to send messages to each other and respond to each other at a fixed interval.

Server code:

package main

import (
    "fmt"
    "net"
    "time"
)

func main() {
    // Start the TCP server    listener, err := ("tcp", ":8080")
    if err != nil {
        ("Error starting server:", err)
        return
    }
    defer ()

    ("Server is listening on port 8080")

    for {
        conn, err := ()
        if err != nil {
            ("Error accepting connection:", err)
            continue
        }
        go handleConnection(conn)
    }
}

func handleConnection(conn ) {
    defer ()
    buffer := make([]byte, 1024)

    for {
        // Read data        n, err := (buffer)
        if err != nil {
            ("Connection closed:", err)
            return
        }
        ("Received:", string(buffer[:n]))

        // Respond to heartbeat messages        if string(buffer[:n]) == "pong" {
            ([]byte("pong"))
        }
    }
}

Client code:

package main

import (
    "fmt"
    "net"
    "time"
)

func main() {
    // Connect to the server    conn, err := ("tcp", "localhost:8080")
    if err != nil {
        ("Error connecting to server:", err)
        return
    }
    defer ()

    // Define the heartbeat interval    ticker := (2 * )
    defer ()

    go func() {
        for {
            <-
            _, err := ([]byte("ping"))
            if err != nil {
                ("Error sending heartbeat:", err)
                return
            }
            ("ping")
        }
    }()

    // Read server response    buffer := make([]byte, 1024)
    for {
        n, err := (buffer)
        if err != nil {
            ("Error reading from server:", err)
            return
        }
        ("Received:", string(buffer[:n]))
    }
}

This is the end of this article about the implementation of socket heartbeat detection in GoLang. For more related content on GoLang socket heartbeat detection, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!