之前说过http的请求是再tcp连接上面进行发送的,那么tcp连接就分为长连接 和 短连接这样的概念,那么什么是长链接呢?http请求发送的时候要先去创建一个tcp的连接,然后在tcp的连接上面发送http请求,请求完以后,客户端会跟服务端商量要不要关闭这个连接,有时候这个创建关闭的过程比保持长链接还要消耗资源
怎么判断这个请求是否是长链接呢,req,res里面会返回一个Connection:Keep-Alive,这个就是保持长链接,不关闭
//server.js const http = require('http'); const fs = require('fs'); http.createServer(function(req,res){ console.log('req come', req.url); const html = fs.readFileSync('test.html', 'utf8'); const img = fs.readFileSync('test.jpg'); if (req.url === '/'){ res.writeHead(200, { 'Content-Type': 'text/html' }) res.end(html); } else { res.writeHead(200, { 'Content-Type': 'image/jpg' }) res.end(img); } }).listen(8888); console.log('server listening on 8888'); console.log('http://localhost:8888/');
<!--test.html--> <body> <img src="/test1.jpg" alt=""> <img src="/test2.jpg" alt=""> <img src="/test3.jpg" alt=""> <img src="/test4.jpg" alt=""> <img src="/test5.jpg" alt=""> <img src="/test6.jpg" alt=""> <img src="/test7.jpg" alt=""> </body>
![](https://img2018.cnblogs.com/blog/331769/201812/331769-20181210065914287-1666482948.png)
如图,返回了8张图片,虽然图片是同一张图片,但是我们的url是不一样的,所以浏览器在发起请求之前就知道这张图片是否一样,他只是根据url来定义不同的资源,所以同样的图片,但浏览器认为是不一样的图片再看
每一个connection-id都是一个请求,浏览器是有并发限制的,一次最多只能6个,现在我们看res,req的Connection改成close会怎么样,Connection只有两种,一个是keep-alive,一个是close,close代表一个tcp请求之后,这个链接就会关闭掉
可以看到每个id都是不一样的,http2的同一个域名允许整站并发,比如google已经采用http2的了,会看到整站都是一个connect-id(相对于同一个域名)