在HTTP/1.0中,默認使用的是短連接。即瀏覽器和服務(wù)器每進行一次HTTP操作,就建立一次連接,但任務(wù)結(jié)束就中斷連接。若客戶端瀏覽器訪問的某個HTML或其他類型的 Web頁中包含有其他的Web資源,如JavaScript文件、圖像文件、CSS文件等;當瀏覽器每遇到這樣一個Web資源,就會建立一個HTTP會話。
從 HTTP/1.1起,默認使用長連接,用以保持連接特性。使用長連接的HTTP協(xié)議,會在響應頭有加入這行代碼:Connection:keep-alive
在使用長連接的情況下,當一個網(wǎng)頁打開完成后,客戶端和服務(wù)器之間用于傳輸HTTP數(shù)據(jù)的 TCP連接不會關(guān)閉,如果客戶端再次訪問這個服務(wù)器上的網(wǎng)頁,會繼續(xù)使用這一條已經(jīng)建立的連接。Keep-Alive不會永久保持連接,它有一個保持時間,可以在不同的服務(wù)器軟件中設(shè)定這個時間。
HTTP協(xié)議的長連接和短連接,實質(zhì)上是TCP協(xié)議的長連接和短連接。
如圖可以通過chrome右鍵新增connectionID來判斷資源是否使用的同一個連接拓展,chrome的devTools中,信息列可以開啟priority和connectionID來查看請求資源的請求優(yōu)先級別和采用的連接
connectionID
為了優(yōu)化網(wǎng)頁的加載速度,可以考慮從waterfall進行分析入手,首先waterfall越短越好(表示請求的資源越少);waiting(TTFB) 時間越短越好(從服務(wù)器端響應進行優(yōu)化);重要資源從waterfall中越左邊越好(即請求優(yōu)先級的不同)
參考鏈接:https://www.cnblogs.com/shengulong/p/7449927.html
demo
//server.js
const http=require('http');
const fs=require('fs')
http.createServer(function(request,response){
const img=fs.readFileSync('test.jpg')
if (request.url==='/') {
const html=fs.readFileSync('test.html','utf8')
response.writeHead(200,{
'Content-Type':'text/html',
'Set-Cookie':['id=123;max-age=10','abc=456;HttpOnly','test=789;domain=test.com']
})
response.end(html)
}else{
response.writeHead(200,{
'Content-Type':'image/jpg',
})
response.end(img)
}
}).listen(8888)
console.log('server listening on 8888')
//test.html
<html>
<head>
<title>3-7 HTTP長連接</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</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="/test11.jpg">
<img src="/test12.jpg">
<img src="/test13.jpg">
<img src="/test14.jpg">
<img src="/test15.jpg">
<img src="/test16.jpg">
<img src="/test21.jpg">
<img src="/test22.jpg">
<img src="/test23.jpg">
<img src="/test24.jpg">
<img src="/test25.jpg">
<img src="/test26.jpg">
</body>
<script type="text/javascript">
</script>
</html>

默認:'Connection':'keep-alive'
如圖所示,其中有六個tcp連接分別被復用了三次
當我們設(shè)置'Connection':'close'時:
const http=require('http');
const fs=require('fs')
http.createServer(function(request,response){
const img=fs.readFileSync('test.jpg')
if (request.url==='/') {
const html=fs.readFileSync('test.html','utf8')
response.writeHead(200,{
'Content-Type':'text/html',
'Set-Cookie':['id=123;max-age=10','abc=456;HttpOnly','test=789;domain=test.com']
})
response.end(html)
}else{
response.writeHead(200,{
'Content-Type':'image/jpg',
'Connection':'close'
})
response.end(img)
}
}).listen(8888)
console.log('server listening on 8888')

'Connection':'close'
如圖所示:每個資源都創(chuàng)建了一條tcp連接
總結(jié)
長鏈接可以設(shè)置timeout
同個tcp內(nèi)是有先后順序的
chrome瀏覽器可以并發(fā)6個tcp
Connection:keep-alive(長)、close(短)
http2:信道復用 ,同域下,tcp并發(fā)發(fā)送http請求
http請求是在tcp上發(fā)送的,一個tcp可以發(fā)送多個http,http1.1是阻塞的
