HTTP(Ⅷ)—— 长连接

HTTP连接分为长连接和短连接,因为HTTP发送请求之前客户端和服务器要进行连接。目前基本上都是保持长连接。

接下来进行测试:

server.js

const http = require('http')
const fs = require('fs')
http.createServer(function(request, response) {
    console.log('request come', request.url)
    const html = fs.readFileSync('test.html', 'utf8')
    const img = fs.readFileSync('test.jpg')
   if(request.url === '/'){
       response.writeHead(200, {
           'Content-Type': 'text/html'
       })
       response.end(html)
   } else {
       response.writeHead(200, {
           'Content-Type': 'img/jpg'
       })
       response.end(img)
   }
}).listen(8888)
console.log('server listening on 8888')

test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<img src="/test1.jpg">
<img src="/test2.jpg">
<img src="/test3.jpg">
<img src="/test4.jpg">
<img src="/test5.jpg">
<img src="/test6.jpg">
<img src="/test7.jpg">
</body>
<script>

</script>
</html>

在同等目录下放入一个test.jpg图片,然后启动服务,访问localhost:8888,去查看network

我们可以看到后面的watefall后面的test7.jpg在请求时,前面有很长一段灰色的,那这是什么呢?这是他在等待有新的TCP连接空出来,它才能去发送请求,这是浏览器TCP并发连接的限制。

如果我们将connection设置为close会看到下面的状态,它的每一个connection id都是不一样的,而且是越来越大的,是因为每次发送完一个请求,jiuguanbiTCP连接,发送下一个请求,又开始新的TCP连接:

猜你喜欢

转载自blog.csdn.net/zhanghuali0210/article/details/82085260