Files
vibe_coding/.cursor/skills/websocket-service/references/ws-implementation.md
2026-03-05 21:27:11 +08:00

46 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# WebSocket Service — 实现细节
> 主流程见 SKILL.md本文档为服务端配置、连接管理器、Controller、推送服务、前端客户端的完整代码。
## 服务端配置
```php
// config/autoload/server.php
[
'name' => 'ws',
'type' => Server::SERVER_WEBSOCKET,
'host' => '0.0.0.0',
'port' => (int) env('WEBSOCKET_PORT', 9502),
'callbacks' => [
Event::ON_HAND_SHAKE => [Hyperf\WebSocketServer\Server::class, 'onHandShake'],
Event::ON_MESSAGE => [...],
Event::ON_CLOSE => [...],
],
]
```
## 连接管理器
WebSocketConnectionManagerRedis HASH `ws:conn:{fd}` 存 user_id/server_id/connected_at。Redis SET `ws:user:{userId}``{serverId}:{fd}`支持多连接。addConnection、removeConnection、getUserConnections、getUserIdByFd、isOnline。
## WebSocket Controller
OnOpenInterface从 query token 验证 JWT无效则 close。addConnection。push connected 消息。OnMessageInterface解析 typeping→pong。OnCloseInterfaceremoveConnection。validateToken 返回 userId。
## 消息推送服务
WebSocketPushServicepushToUser(userId, type, data) 遍历 getUserConnectionsSender->push。pushToUsers 循环 pushToUser。broadcast 用 Redis publish 跨服务器。
## 前端 WebSocketClient
```typescript
class WebSocketClient {
constructor(url, token) {}
connect() { this.ws = new WebSocket(`${url}?token=${token}`) }
onmessage emit(type, data)
on(type, callback) unsubscribe
startHeartbeat() 30s ping
onclose scheduleReconnect 退
}
```