本文代码及背景介绍参考:https://socket.io/get-started/webtransport。相比原文章,提供中文版操作说明,将原文中复杂指令替换为更简单可行的命令,并提供额外的debug指导。但本文仅提供最终版本的代码,如需了解WebTransport版本代码与WebSocket版本代码的差异,请参考原文。
背景
Socket.IO 4.7.0版本(2023 年 6 月)增加了对 WebTransport 的支持。简而言之,WebTransport 是 WebSocket 的替代品,它解决了困扰 WebSocket 的几个性能问题,例如队头阻塞。
工作目录结构
Project
|-- cert (存放证书)
|--localhost+2.pem(cert文件)
|--localhost+2-key.pem(key文件)
|--node_modules(Node依赖包)
|-- ……
|--index.html(客户端)
|--index.js(服务端)
|--package.json(项目说明及依赖包引入)
Package.json
{
"name": "ProjectName",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@fails-components/webtransport": "^1.4.1",
"@fails-components/webtransport-transport-http3-quiche": "^1.4.1",
"socket.io": "^4.8.1"
}
}
依赖安装方法:npm i @fails-components/webtransport socket.io
⚠️注意:普通WebTransport是不支持HTTP3的,需要引入@fails-components/webtransport。该项目提供了quiche实现,支持HTTP3。此外,socket.io版本需要>4.7.0。
证书生成
使用mkcert为localhost生成证书(仅用于测试环境):
mkcert localhost 127.0.0.1 ::1
在当前目录下得到两个文件localhost+2.pem和localhost+2-key.pem。将其放入certs目录下(个人偏好,不放进去也可以)。
然后将本机mkcert加入系统受信任根证书颁发机构:
mkcert --install
命令行返回⬇️即为添加成功。
Created a new local CA 💥
Sudo password:
The local CA is now installed in the system trust store! ⚡️
服务端代码(index.js)
import {
readFile } from "node:fs/promises";
import {
createServer } from "node:https";
import {
Server} from "socket.io";
import {
Http3Server } from "@fails-components/webtransport";
import {
randomBytes } from 'crypto';
// const key = await readFile("./certs/localhost.key");
// const cert = await readFile("./certs/localhost.crt");
const key = await readFile("./certs/localhost+2-key.pem");
const cert = await readFile("./certs/localhost+2.pem");
const httpsServer = createServer({
key,
cert
}, async


1975

被折叠的 条评论
为什么被折叠?



