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