dousong5161 2017-11-19 15:10
浏览 58
已采纳

http.Server的怪异行为-为每个客户端建立三个连接?

I'm a noob Go programmer. I'm currently writing a web application which streams data to clients. To test if it works well, I've wrote this code(streaming.go):

package main

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

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("X-Content-Type-Options", "nosniff")

    fmt.Println("Client connected!")

    flusher, ok := w.(http.Flusher)
    if !ok {
        fmt.Println("ResponseWriter doesn't implement Flusher interface")
        return
    }

    closeNotifier, ok := w.(http.CloseNotifier)
    if !ok {
        fmt.Println("ResponseWriter doesn't implement CloseNotifier interface")
        return
    }
    closeNotifyChannel := closeNotifier.CloseNotify()

    for {
        fmt.Println("Sending data chunk...")
        fmt.Fprintf(w, "Chunk.")
        flusher.Flush()

        select {
        case <-closeNotifyChannel:
            goto closed
        default:
            time.Sleep(500 * time.Millisecond)
        }
    }

closed:
    fmt.Println("Client disconnected")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", handler)

    server := &http.Server{
        Addr:    "localhost:8000",
        Handler: mux,
        ConnState: func(conn net.Conn, state http.ConnState) {
            fmt.Printf("[ConnState] %v: ", conn.RemoteAddr())

            switch state {
            case http.StateNew:
                fmt.Println("StateNew")
            case http.StateActive:
                fmt.Println("StateActive")
            case http.StateIdle:
                fmt.Println("StateIdle")
            case http.StateHijacked:
                fmt.Println("StateHijacked")
            case http.StateClosed:
                fmt.Println("StateClosed")
            }
        },
    }

    server.ListenAndServe()
}

What it does is: 1. When a client has connected, get http.Flusher and http.CloseNofier instance for http.ResponseWriter 2. Send little amount of data(chunk) until client is disconnected(in this example I used simple string, "Chunk.")

Here's a sample output for this program when I enter 127.0.0.1:8000 in my Chrome browser:

[ConnState] 127.0.0.1:57226: StateNew
[ConnState] 127.0.0.1:57227: StateNew
[ConnState] 127.0.0.1:57228: StateNew
[ConnState] 127.0.0.1:57226: StateActive
Client connected!
Sending data chunk...
Sending data chunk...
Sending data chunk...
Sending data chunk...
Sending data chunk...
Sending data chunk...
Sending data chunk...
[ConnState] 127.0.0.1:57227: StateActive
Client connected!
Sending data chunk...
Sending data chunk...
Client disconnected
[ConnState] 127.0.0.1:57226: StateIdle
[ConnState] 127.0.0.1:57226: StateClosed
Sending data chunk...
Sending data chunk...
Sending data chunk...
Sending data chunk...
...(forever)

So what the hack are those 127.0.0.1:57227, 127.0.0.1:57228? They don't get activated as soon as client connected but when I press ESC key in my browser, one gets activated. Where does my handler send data to?

I'm wondering if Connection: keep-alive(seems that Chrome automatically adds this header for request) makes this happens, please let me know what I'm missing. Thanks.

  • 写回答

1条回答 默认 最新

  • duanfengshang1088 2017-11-19 15:56
    关注

    I don't think you are missing anything here. Chrome might have opened multiple connection to your server, may be hoping that there may be many parallel requests to the remote server. Chrome may open upto 6 connections to a server for issuing requests in parallel to that server. But as there is just one GET call from the browser in your test here, so the data transfer is happening only over one of those sockets (or connections) opened. As 2 of the connections (sockets) are not getting data, they may get closed due to idle timeout from client or server side. If you are running the program from Linux/Mac etc., you may check how the data getting transferred over which socket by using Tcpdump. Or alternatively, you may use Wireshark also to inspect the HTTP or TCP traffics and that will give you clear picture of what is happening over those sockets. May be some tcpdump command like the one shown below will help:

      $ sudo tcpdump -i lo0 port 8000  -s 65534 -A
        Eg. tcpdump -i <interface> port <some port> -s <max-packet-capture-size>  -A
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加