GO语言模拟长轮询代码

107人浏览 / 0人评论

服务端:

package main

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

func handleRequest(w http.ResponseWriter, r *http.Request) {
    // 设置长链接头
    w.Header().Set("Connection", "keep-alive")
    w.Header().Set("Keep-Alive", "timeout=5, max=1000")

    // 读取请求体
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Println("Error reading request body:", err)
        http.Error(w, "Error reading request body", http.StatusBadRequest)
        return
    }
    defer r.Body.Close()

    // 处理请求
    fmt.Println("Received request:", string(body))

    // 发送响应
    w.Write([]byte("Request received"))
}

func main() {
    http.HandleFunc("/", handleRequest)
    fmt.Println("Server listening on http://localhost:7878")
    http.ListenAndServe(":7878", nil)
}

 

客户端代码

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
    "sync"
    "time"
)

func sendRequest(client *http.Client, wg *sync.WaitGroup, requestCount int) {
    defer wg.Done()

    for i := 0; i < requestCount; i++ {
        // 构造POST请求体
        data := []byte(fmt.Sprintf("Request Data: %d", i))
        req, err := http.NewRequest("POST", "http://link.tongdao.cn", bytes.NewBuffer(data))
        if err != nil {
            fmt.Println("Error creating request:", err)
            continue
        }

        // 设置长链接头
        req.Header.Set("Connection", "keep-alive")

        // 发送请求
        resp, err := client.Do(req)
        if err != nil {
            fmt.Println("Error sending POST request:", err)
            continue
        }

        // 读取响应内容
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            fmt.Println("Error reading response body:", err)
            resp.Body.Close()
            continue
        }
        resp.Body.Close()

        fmt.Println("Response:", string(body))

        // 每1秒发送一次请求
        time.Sleep(20 * time.Second)
    }
}

func main() {
    client := &http.Client{
        Transport: &http.Transport{
            DisableKeepAlives: false, // 启用长链接
        },
    }

    var wg sync.WaitGroup
    concurrency := 10 // 并发数
    requestCount := 1000 // 每个goroutine发送的请求数

    for i := 0; i < concurrency; i++ {
        wg.Add(1)
        go sendRequest(client, &wg, requestCount)
    }

    wg.Wait()
}

 

全部评论