http长连接keep-alive

connection

close:短连接,每次请求都建立一个TCP连接
Keep-Alive:长链接,使浏览器可以在一个TCP/IP连接中做多次请求,性能更高;chrome允许并发的TCP连接数是6
HTTP1.0默认false,HTTP1.1默认是keep-alive
HTTP2信道复用,可以在一个TCP连接上并发同域请求,如谷歌官网。

实例

node服务器:server.js

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-alive' // or close
    })
    response.end(img)
  }

}).listen(8888)

console.log('server listening on 8888')

test.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <img src="/test1.jpg" alt="">
  <img src="/test2.jpg" alt="">
  <img src="/test3.jpg" alt="">
  <img src="/test4.jpg" alt="">
  <img src="/test5.jpg" alt="">
  <img src="/test6.jpg" alt="">
  <img src="/test7.jpg" alt="">
  <img src="/test11.jpg" alt="">
  <img src="/test12.jpg" alt="">
  <img src="/test13.jpg" alt="">
  <img src="/test14.jpg" alt="">
  <img src="/test15.jpg" alt="">
  <img src="/test16.jpg" alt="">
  <img src="/test17.jpg" alt="">
  <img src="/test111.jpg" alt="">
  <img src="/test112.jpg" alt="">
  <img src="/test113.jpg" alt="">
  <img src="/test114.jpg" alt="">
  <img src="/test115.jpg" alt="">
  <img src="/test116.jpg" alt="">
  <img src="/test117.jpg" alt="">
</body>
</html>

1.文件目录下命令行输入node server,开启8888端口服务
2.打开开发者调试工具,浏览器地址栏输入localhost:8888,回车
3.在Network的Name栏右键-勾选Connection ID,即TCP连接的ID,并将请求以Waterfall排序
4.可以观察到共有6种Connection ID,test7.jpg是在前六张图片有请求完成后再调用的请求,即chrome允许的TCP并发数为6,而且当一个请求完成后会在用过的TPC/IP连接上调用其他请求,即Keep-Alive的持久连接。

猜你喜欢

转载自blog.csdn.net/qq_31393401/article/details/81233792
今日推荐