1.6 KiB
1.6 KiB
WebSocket Service — 实现细节
主流程见 SKILL.md,本文档为服务端配置、连接管理器、Controller、推送服务、前端客户端的完整代码。
服务端配置
// 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 => [...],
],
]
连接管理器
WebSocketConnectionManager:Redis 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:解析 type,ping→pong。OnCloseInterface:removeConnection。validateToken 返回 userId。
消息推送服务
WebSocketPushService:pushToUser(userId, type, data) 遍历 getUserConnections,Sender->push。pushToUsers 循环 pushToUser。broadcast 用 Redis publish 跨服务器。
前端 WebSocketClient
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 指数退避
}