GO语言模拟长链接代码

92人浏览 / 0人评论

服务端代码

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func handleConnection(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, "Method is not supported.", http.StatusNotFound)
        return
    }

    // 设置HTTP头部,允许长连接
    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")
    w.Header().Set("Access-Control-Allow-Origin", "*")

    // 设置客户端每隔5秒发送一次心跳
    flusher, ok := w.(http.Flusher)
    if !ok {
        http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
        return
    }

    for {
        // 向客户端发送当前时间
        fmt.Fprintf(w, "The time is now: %s\n", time.Now().Format(time.RFC3339))
        flusher.Flush() // 刷新缓冲区,确保数据发送到客户端

        time.Sleep(1 * time.Second) // 等待5秒
    }
}

func main() {
    http.HandleFunc("/", handleConnection)

    fmt.Printf("Starting server at port 7878\n")
    if err := http.ListenAndServe(":7878", nil); err != nil {
        log.Fatal(err)
    }
}
 

客户端代码

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
)

func main() {
    resp, err := http.Get("http://www.liangzeyu.com/")
    if err != nil {
        log.Fatalf("Error fetching stream: %v", err)
    }
    defer resp.Body.Close()

    fmt.Println("Connected to server")
    buf := make([]byte, 1024)
    for {
        n, err := resp.Body.Read(buf)
        if err != nil && err != io.EOF {
            log.Fatalf("Error reading stream: %v", err)
        }
        fmt.Print(string(buf[:n]))
    }
}

 

全部评论