前言:
發起http請求時,會通過tcp三次通信建立連接connection,而在http1.1協議中默認會使用長連接保存連接。而如果服務端返回的響應頭中包含'Connection': 'keep-close',則每次請求都會建立新的連接。
以下是服務端代碼:
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': 'image/jpg',
'Connection': 'keep-close' // or live
})
response.end(img)
}
}).listen(8888)
console.log('server listening on 8888')
如圖:
