Skip to content

HTTP2协议

🕒 Published at:

HTTP2简介

基于HTTPS

HTTP2支持了

  1. 二进制分帧。真正的解决了共享TCP连接时的队头阻塞问题,实现了真正的多路复用

报文使用二进制传输,减小了体积,提升了传输效率可以设置传输优先级,不同的流可以交替传输。

  1. 消息头压缩。可以减少20%-30%的体积,客户端和服务端会维护一张静态表和一张动态表,通过编号来表示某个字段
  2. Server push技术。HTTP2允许在客户端没有主动请求的情况下,服务器预先把资源推送给客户端,当客户端后续需要请求该资源时,则自动从之前推送的资源中寻找。

使用Node.js编写HTTP2服务

可以使用Node.js内置模块http2编写HTTP2服务

typescript
// main.ts
// import { createSecureServer } from 'node:http2'
import { readFileSync } from 'node:fs'
import { getDirname } from '@oliver_lou/utils'
import path from 'node:path'
const __dirname = getDirname(import.meta.url)

// Node.js ESM判断是否支持HTTP2模块
let http2;
try {
  // v16.13.1支持顶层await
  http2 = await import('node:http2');
  console.log(`http2 is support.`)
} catch (err) {
  console.error('http2 support is disabled!');
}

const server = http2.createSecureServer({
  key: readFileSync(path.resolve(__dirname, 'localhost-key.pem')),
  cert: readFileSync(path.resolve(__dirname, 'localhost.pem')),
})
server.on('error', (err) => console.error(err))

server.on('stream', (stream, headers) => {
  // stream is a Duplex
  stream.respond({
    'content-type': 'text/html; charset=utf-8',
    ':status': 200,
  })
  stream.end('<h1>Hello HTTP2!</h1>')
})

const port = 8443
server.listen(port, () => {
  console.log(`server at https://localhost:${port}`)
})

启动服务

sh
npm i -g tsx
pnpm i @oliver_lou/utils
tsx main.ts

https证书可以使用mkcert生成

sh
mkcert localhost

使用nginx部署HTTP2服务

nginx v1.9.5+支持HTTP2

通过listen选项配置HTTP2

nginx
server {
    listen  443 ssl http2;
    server_name  localhost;
    ssl_certificate     localhost.pem;
    ssl_certificate_key localhost-key.pem;
    ssl_session_timeout 5m;
    ssl_session_timeout  5m;
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;

    location / {
           root   html;
           index  index.html index.htm;
    }
}

通过http2选项配置HTTP2

nginx
server {
       listen       443 ssl;
       http2   on;
       server_name  localhost;
       ssl_certificate      localhost.pem;
       ssl_certificate_key  localhost-key.pem;

       ssl_session_cache    shared:SSL:1m;
       ssl_session_timeout  5m;

       ssl_ciphers  HIGH:!aNULL:!MD5;
       ssl_prefer_server_ciphers  on;

       location / {
           root   html;
           index  index.html index.htm;
       }
    }