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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料