初始化

This commit is contained in:
2026-03-05 21:27:11 +08:00
commit 130de0fd5d
140 changed files with 21972 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
# 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 退
}
```