前言:
发起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')
如图: