自学内容网 自学内容网

【GoLang】socket 心跳检测的实现

心跳检测是确保服务端与客户端之间稳定性的一种机制,具体实现方法为每间隔固定时间相互发送消息并响应。

服务端代码:

package main

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

func main() {
    // 启动 TCP 服务器
    listener, err := net.Listen("tcp", ":8080")
    if err != nil {
        fmt.Println("Error starting server:", err)
        return
    }
    defer listener.Close()

    fmt.Println("Server is listening on port 8080")

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

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

    for {
        // 读取数据
        n, err := conn.Read(buffer)
        if err != nil {
            fmt.Println("Connection closed:", err)
            return
        }
        fmt.Println("Received:", string(buffer[:n]))

        // 响应心跳消息
        if string(buffer[:n]) == "pong" {
            conn.Write([]byte("pong"))
        }
    }
}

客户端代码:

package main

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

func main() {
    // 连接到服务器
    conn, err := net.Dial("tcp", "localhost:8080")
    if err != nil {
        fmt.Println("Error connecting to server:", err)
        return
    }
    defer conn.Close()

    // 定义心跳间隔
    ticker := time.NewTicker(2 * time.Second)
    defer ticker.Stop()

    go func() {
        for {
            <-ticker.C
            _, err := conn.Write([]byte("ping"))
            if err != nil {
                fmt.Println("Error sending heartbeat:", err)
                return
            }
            fmt.Println("ping")
        }
    }()

    // 读取服务器响应
    buffer := make([]byte, 1024)
    for {
        n, err := conn.Read(buffer)
        if err != nil {
            fmt.Println("Error reading from server:", err)
            return
        }
        fmt.Println("Received:", string(buffer[:n]))
    }
}


原文地址:https://blog.csdn.net/2201_75692232/article/details/144197073

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!