WebSocketHTML5HTTPAPIWebSocket
WebSocketiframeWebSocket2011RFC 6455
WebSocketTCPHTTP80443HTTPUpgradeHTTP
WebSocket 握手机序(详细版)
sequenceDiagram
participant B as 浏览器
participant S as WebSocket服务器
Note over B,S: HTTP 升级请求
B->>S: GET /ws HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
S->>B: HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYG3hZb==
Note over B,S: 握手成功,TCP 长连接建立
loop 全双工通信
B->>S: Text/Binary Frame
S->>B: Text/Binary Frame
end
WebSocket vs HTTP 对比
flowchart LR
subgraph HTTP["HTTP"]
H1["请求-响应模式"]
H2["每次请求新建连接(1.1需keep-alive)"]
H3["服务端无法主动推送"]
H4["头部开销大( KB级)"]
end
subgraph WS["WebSocket"]
W1["全双工长连接"]
W2["一次握手,持续连接"]
W3["服务端可随时推送"]
W4["头部极小(2字节帧头)"]
end
style HTTP fill:#e74c3c,color:#fff
style WS fill:#27ae60,color:#fff
| | HTTP | WebSocket |
| --- | --- | --- |
| | | |
| | | |
| | / | |
| | | |
| | | |
WebSocketHTTP
HTTPWebSocketHTTP
WebSocket API
WebSocket 生命周期状态机
stateDiagram-v2
[*] --> CONNECTING : new WebSocket()
CONNECTING --> OPEN : 服务器101响应
OPEN --> CLOSING : close() 调用
OPEN --> CLOSED : 连接失败/超时
OPEN --> ERROR : 网络错误
CLOSING --> CLOSED : 收到关闭帧
CLOSED --> [*]
ERROR --> [*]
// WebSocketwssWebSocketHTTPSwsHTTP
const socket = new WebSocket('wss://example.com/ws');
WebSocket
//
socket.addEventListener('open', (event) => {
console.log('WebSocket');
//
socket.send('Hello Server!');
});
//
socket.addEventListener('message', (event) => {
console.log(':', event.data);
});
//
socket.addEventListener('error', (error) => {
console.error('WebSocket:', error);
});
//
socket.addEventListener('close', (event) => {
console.log('WebSocket:', event.code, event.reason);
});
sendBlobArrayBuffer
//
socket.send('');
// JSON
const data = { type: 'chat', content: '' };
socket.send(JSON.stringify(data));
//
const buffer = new ArrayBuffer(8);
socket.send(buffer);
close
// codereason
socket.close(1000, '');
WebSocketNode.jswsWebSocket
ws
npm install ws
const WebSocket = require('ws');
// WebSocket8080
const wss = new WebSocket.Server({ port: 8080 });
//
wss.on('connection', (ws) => {
console.log('');
//
ws.on('message', (message) => {
console.log(':', message.toString());
//
ws.send(: ${message});
//
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(: ${message});
}
});
});
//
ws.on('close', () => {
console.log('');
});
});
console.log('WebSocket8080');
WebSocket
JSONtypedata
WebSocket为Web应用带来了真正的实时通信能力,是现代交互式Web应用的重要技术。
想要学习更多网络协议知识,可以继续阅读我们的HTTP协议详解和TCP/IP入门教程。对于需要测试正则表达式的开发者,我们的正则表达式测试工具会很有帮助。