WebSocket 是一种在单个 TCP 连接上提供全双工通信的网络协议,由 Ian Hickson 于 2008 年提出,2011 年成为 RFC 6455 标准。WebSocket 允许服务器主动向客户端推送数据,是实现 实时 Web 应用 的核心技术。
WebSocket 的核心定位是 实时的双向通信。它提供了:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: http://example.com
// 服务器响应
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
// 创建 WebSocket 连接
const ws = new WebSocket('ws://localhost:8080/chat');
// 连接建立
ws.onopen = function(event) {
console.log('WebSocket 连接已建立');
ws.send('Hello, Server!');
};
// 接收消息
ws.onmessage = function(event) {
console.log('收到消息:', event.data);
};
// 连接关闭
ws.onclose = function(event) {
console.log('WebSocket 连接已关闭', event.code);
};
// 错误处理
ws.onerror = function(error) {
console.error('WebSocket 错误:', error);
};
// 发送消息
ws.send('{"type":"chat","content":"Hello World"}');
// 关闭连接
ws.close();
// 检查连接状态
console.log(ws.readyState); // 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED
// 使用 ws 库
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
// 处理客户端连接
wss.on('connection', function connection(ws, req) {
console.log('客户端已连接');
// 接收消息
ws.on('message', function incoming(message) {
console.log('收到消息: %s', message);
// 广播给所有客户端
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// 发送消息
ws.send('欢迎连接到 WebSocket 服务器!');
// 连接关闭
ws.on('close', function() {
console.log('客户端已断开');
});
});
// 心跳检测
wss.on('connection', function connection(ws) {
ws.isAlive = true;
ws.on('pong', function() {
ws.isAlive = true;
});
});
const interval = setInterval(function ping() {
wss.clients.forEach(function each(ws) {
if (ws.isAlive === false) {
return ws.terminate();
}
ws.isAlive = false;
ws.ping();
});
}, 30000);
// 使用 Swoole 实现 WebSocket
use Swoole\WebSocket\Server;
$server = new Server('0.0.0.0', 9502);
// 处理连接打开
$server->on('open', function($server, $request) {
echo "连接建立: {$request->fd}\n";
$server->push($request->fd, "欢迎来到 WebSocket 服务器!");
});
// 处理接收消息
$server->on('message', function($server, $frame) {
echo "收到消息: {$frame->data}\n";
// 广播给所有客户端
foreach ($server->connections as $fd) {
if ($fd !== $frame->fd) {
$server->push($fd, $frame->data);
}
}
});
// 处理连接关闭
$server->on('close', function($server, $fd) {
echo "连接关闭: {$fd}\n";
});
$server->start();
# 使用 websockets 库
import asyncio
import websockets
async def handler(websocket, path):
async for message in websocket:
print(f"收到消息: {message}")
# 广播给所有客户端
for ws in websockets.clients:
if ws != websocket:
await ws.send(message)
async def main():
async with websockets.serve(handler, "localhost", 8765):
await asyncio.Future() # 永久运行
asyncio.run(main())
// Spring Boot WebSocket 配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
// WebSocket 控制器
@Controller
public class WebSocketController {
@MessageMapping("/chat")
@SendTo("/topic/messages")
public String handleMessage(String message) {
return "收到: " + message;
}
}
WebSocket 原理、握手流程、数据帧结构、前端 API
Node.js/ws、Python/websockets、PHP/Swoole、Java/Spring Boot
心跳检测、断线重连、消息压缩、子协议
实时聊天室、在线游戏、协同编辑、实时监控
WebSocket 是 Web 实时通信的高速公路。
它用 全双工通信、持久连接、低延迟 解决了 HTTP 协议在实时场景下的不足。WebSocket 是构建现代实时 Web 应用(聊天、游戏、协同编辑)的核心技术。
掌握 WebSocket,意味着你能 构建高性能的实时 Web 应用、实现服务器主动推送。
"WebSocket 让 Web 应用从请求-响应走向了实时双向。" 🔄