如果content-length错误,Chrome将关闭tcp连接?

时间:2019-02-13 13:11:23

标签: http go tcp

我对Web服务器对http keep-alive标头的操作感兴趣。因此,我基于http服务器构建了一个简单的http服务器。服务器只通过简单的html http正文对客户端做出响应。

服务器代码在这里:

package main

import (
    "fmt"
    "net"
    "os"
)

func main() {
    l, err := net.Listen("tcp", "localhost:9765")
    if err != nil {
        fmt.Println("Error listening:", err.Error())
        os.Exit(1)
    }
    defer l.Close()
    for {
        conn, err := l.Accept()
        fmt.Println("New connection...")
        if err != nil {
            fmt.Println("Error accepting: ", err.Error())
            os.Exit(1)
        }
        go handleRequest(conn)
    }
}

// handler
func handleRequest(conn net.Conn) {
    for {
        buf := make([]byte, 512)
        _, err := conn.Read(buf)
        if err != nil {
            fmt.Println("Error reading:", err.Error())
            conn.Close()
            break
        }
        fmt.Printf("%s", buf)
        str := `HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 8
Content-Type: application/javascript

alert(1)

`
        conn.Write([]byte(str))
    }
}

我向本地nginx静态服务器添加了一个演示html:          

<head>
    <meta charset="UTF-8">
    <script type=text/javascript src="test.js"></script>
    <script type=text/javascript src="http://localhost:9765/3"></script>
    <script type=text/javascript src="http://localhost:9765/2"></script>
    <script type=text/javascript src="http://localhost:9765/1"></script>
    <script type=text/javascript src="http://localhost:9765/17"></script>
    <script type=text/javascript src="http://localhost:9765/16"></script>
    <script type=text/javascript src="http://localhost:9765/15"></script>
    <script type=text/javascript src="http://localhost:9765/14"></script>
    <script type=text/javascript src="http://localhost:9765/13"></script>
    <script type=text/javascript src="http://localhost:9765/12"></script>
    <script type=text/javascript src="http://localhost:9765/30"></script>
    <script type=text/javascript src="http://localhost:9765/29"></script>
    <script type=text/javascript src="http://localhost:9765/28"></script>
    <script type=text/javascript src="http://localhost:9765/27"></script>
    <script type=text/javascript src="http://localhost:9765/26"></script>
    <script type=text/javascript src="http://localhost:9765/25"></script>
    <script type=text/javascript src="http://localhost:9765/24"></script>
    <script type=text/javascript src="http://localhost:9765/23"></script>
    <script type=text/javascript src="http://localhost:9765/22></script>
    <script type=text/javascript src="http://localhost:9765/21"></script>
</head>

<body>
<h1>loader测试页面</h1>
<span>hello world</span>
</body>

</html>

当使用chrome浏览文件时,我发现所有响应都是正常的,但是在每个http请求之后tcp连接已关闭。发送http响应后,TCP收到EOF错误。

1 个答案:

答案 0 :(得分:3)

如果您在标头中发送了错误的内容长度,浏览器将挂起(等待永远不会出现的内容)或关闭连接(当在内容之后看到无效的垃圾时)。它还能做什么?

相关问题