title: HTTP长连接 date: 2018-09-22 09:59:08 toc: true categories:
- [web前端,HTTP] tags:
- HTTP
长连接的概念
HTTP 的请求是在 TCP 连接的基础上发送的,而 TCP链接分为长连接和短连接 。
长连接:HTTP 发送请求时,要先创建一个 TCP 连接,并在 TCP 连接上把 HTTP 请求的内容发送并且接收完返回,这是一次请求完成,浏览器与服务器进行协商是否关闭 TCP 链接,若不关闭 TCP 连接会有一定的消耗,好处是如果还有请求可以直接在这个 TCP 连接上发送,不需要经过创建时三次握手的消耗。
短连接:若关闭 TCP 连接,下次请求需要重新创建,这时会有网络延迟的开销,好处是每次请求完关闭 TCP 连接,减少客户端和服务端连接的并发数。
实际情况中,网站的并发量比较大,如果每次都重新创建连接,导致创建过程发生太多,导致创建 TCP 连接的开销,比保持长连接还要高一些。而且长连接可以设置关闭时间,在一定时间内没有请求自动关闭。一般情况都会保持长连接。
百度示例
示例,打开百度首页,打开控制台-network,name那一行,右键选中 connection ID,代表 tcp 连接 的 id,根据他区分是否是同一个 tcp 连接。
长连接的使用
命令行 node server.js 启动服务,locahost:8888访问,查看 network的 connection ID 和 waterfall。
设置网速 fast 3G
// server.jsconst 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' }) response.end(img) }}).listen(8888)console.log('server listening on 8888')复制代码
// test.html![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
复制代码
Chrome浏览器的 TCP 连接的并发限制,6个 TCP 连接后,第7个 TCP连接有新的 TCP 连接空出来
默认是长连接
关闭长连接
通过设置 'Connection': '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', 'Connection': 'close' // 默认是 keep-alive }) response.end(html) } else { response.writeHead(200, { 'Content-Type': 'image/jpg', 'Connection': 'close' // 默认是 keep-alive }) response.end(img) }}).listen(8888)console.log('server listening on 8888')复制代码
没有重复利用 TCP 连接,并且每个 connection id 都不同
正常情况下都是合理利用 Connection:'keep-alive',并设置一个自动关闭时间,在服务端进行控制
HTTP 2 信道复用
HTTP2 信道复用,在 TCP 连接上可以并发的发送 HTTP 请求,意味着链接网站是只需要一个 TCP 连接。google.com的页面都是用的 HTTP2。
它的 connection id 都是一个,注意,同域 id 才相同,不同域需要创建 tcp 连接,这样降低了开销,速度有质的提升。
总结
http 请求是在 tcp 连接上发送的,一个 tcp 连接可以发送多个 http 请求
在 http 1.1 中 http 请求在 tcp 上进行发送有先后顺序,为了提高性能,需要使用并发 tcp 连接的方式。
在 http 2 中,可以在一个 tcp 连接上并发的发送 http 请求,所以只需要开一个 tcp 连接。
长连接的概念