http長連接


前言:

發起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')

如圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM