更新websocket功能

This commit is contained in:
2026-02-18 18:05:33 +08:00
parent e679a9402f
commit a0c2350662
9 changed files with 1273 additions and 74 deletions

View File

@@ -160,6 +160,11 @@ class WebSocketHandler implements WebSocketHandlerInterface
$data = $message['data'] ?? [];
switch ($type) {
case 'auth':
// Handle authentication confirmation
$this->handleAuth($server, $fd, $data);
break;
case 'ping':
// Respond to ping with pong
$server->push($fd, json_encode([
@@ -212,6 +217,55 @@ class WebSocketHandler implements WebSocketHandlerInterface
}
}
/**
* Handle authentication confirmation
*
* @param Server $server
* @param int $fd
* @param array $data
* @return void
*/
protected function handleAuth(Server $server, int $fd, array $data): void
{
$userId = $data['user_id'] ?? null;
$token = $data['token'] ?? null;
// Get the user ID from wsTable (set during connection)
$storedUserId = $server->wsTable->get('fd:' . $fd)['value'] ?? null;
if ($storedUserId && $storedUserId == $userId) {
// Authentication confirmed, send success response
$server->push($fd, json_encode([
'type' => 'connected',
'data' => [
'user_id' => $storedUserId,
'message' => 'Authentication confirmed',
'timestamp' => time()
]
]));
Log::info('WebSocket authentication confirmed', [
'fd' => $fd,
'user_id' => $userId
]);
} else {
// Authentication failed
$server->push($fd, json_encode([
'type' => 'error',
'data' => [
'message' => 'Authentication failed. User ID mismatch.',
'code' => 401
]
]));
Log::warning('WebSocket authentication failed', [
'fd' => $fd,
'stored_user_id' => $storedUserId,
'provided_user_id' => $userId
]);
}
}
/**
* Handle chat message
*