### Get Body Usage Example Source: https://sockeon.github.io/v3.0/api/response.html Example demonstrating how to retrieve and log the response body. ```php #[HttpRoute('GET', '/api/preview')] public function previewContent(Request $request): Response { $response = Response::ok('

Preview

')->setContentType('text/html'); $body = $response->getBody(); // '

Preview

' // Log the response body error_log("Response body: " . $body); return $response; } ``` -------------------------------- ### Sockeon\Sockeon\Connection\Server::run Source: https://sockeon.github.io/v3.0/api/server.html Starts the server and begins listening for connections. ```APIDOC ## run() ### Description Starts the server and begins listening for connections. This method blocks until the server is stopped. ``` -------------------------------- ### Production Server Configuration Example Source: https://sockeon.github.io/v3.0/core/survivability.html A comprehensive configuration example for a production environment using the Swoole engine. ```php $config = new ServerConfig([ 'engine' => 'swoole', 'survivability' => [ 'max_connections' => 50_000, 'heartbeat_idle_time' => 300, 'heartbeat_check_interval' => 60, ], 'swoole' => [ 'max_connection' => 50_000, 'worker_num' => 8, ], 'rate_limit' => [ 'enabled' => true, 'maxGlobalConnections' => 50_000, 'maxConnectionsPerIp' => 100, ], ]); ``` -------------------------------- ### Install Development Dependencies Source: https://sockeon.github.io/v3.0/getting-started/installation.html Install testing and static analysis tools for development environments. ```bash composer install --dev ``` -------------------------------- ### Install Dependencies Source: https://sockeon.github.io/v3.0/getting-started/quick-start.html Command to install the defined dependencies using Composer. ```bash composer install ``` -------------------------------- ### Install Optional Extensions Source: https://sockeon.github.io/v3.0/getting-started/installation.html Install recommended extensions for high-concurrency or multi-node deployments using PECL. ```bash # High-concurrency single node pecl install openswoole # Multi-node cluster pecl install openswoole redis ``` -------------------------------- ### Basic Server Setup Source: https://sockeon.github.io/v3.0/api/server.html Demonstrates the full lifecycle of configuring, setting up, and running a Sockeon server. ```php '0.0.0.0', 'port' => 6001, 'debug' => true ]); // Create server $server = new Server($config); // Add middleware $server->addHttpMiddleware(CorsMiddleware::class); $server->addWebSocketMiddleware(AuthMiddleware::class); // Register controllers $server->registerController(new ChatController()); $server->registerController(new ApiController()); // Start server $host = $config->getHost(); $port = $config->getPort(); echo "Starting server on {$host}:{$port}\n"; $server->run(); ``` -------------------------------- ### Install OpenSwoole Extension Source: https://sockeon.github.io/v3.0/advanced/swoole-engine.html Command to install the OpenSwoole extension via PECL. ```bash pecl install openswoole ``` -------------------------------- ### Set Body Usage Example Source: https://sockeon.github.io/v3.0/api/response.html Example demonstrating how to set the response body dynamically based on request parameters. ```php #[HttpRoute('GET', '/api/dynamic')] public function dynamicContent(Request $request): Response { $response = new Response(); $format = $request->getQuery('format', 'json'); if ($format === 'xml') { $response->setBody('Hello') ->setHeader('Content-Type', 'application/xml'); } else { $response->setBody('{"message": "Hello"}') ->setHeader('Content-Type', 'application/json'); } return $response; } ``` -------------------------------- ### Complete Server Information Example in PHP Source: https://sockeon.github.io/v3.0/api/server.html Demonstrates aggregating various server metrics into a JSON response. ```php #[HttpRoute('GET', '/api/server-info')] public function getServerInfo(Request $request): Response { $server = $this->getServer(); return Response::json([ 'clients' => $server->getClientCount(), 'uptime' => $server->getUptime(), 'uptime_human' => $server->getUptimeString(), 'start_time' => $server->getStartTime(), 'health_check' => $server->getHealthCheckPath(), ]); } ``` -------------------------------- ### Configure Scaling Settings Source: https://sockeon.github.io/v3.0/getting-started/migration-v3.html Example configuration for enabling Swoole engine and Redis-based scaling. ```php 'engine' => 'swoole', 'scale' => [ 'node_id' => getenv('SOCKEON_NODE_ID') ?: gethostname(), 'publisher' => 'redis', 'registry' => 'redis', 'redis' => [ 'host' => getenv('REDIS_HOST') ?: '127.0.0.1', 'port' => 6379, ], ], ``` -------------------------------- ### Install Redis Extension Source: https://sockeon.github.io/v3.0/getting-started/migration-v3.html Required command to install the Redis extension for scaling features. ```bash pecl install redis ``` -------------------------------- ### Retrieve Server Start Time in PHP Source: https://sockeon.github.io/v3.0/api/server.html Returns the Unix timestamp of when the server started. ```php public function getStartTime(): ?float ``` ```php $startTime = $server->getStartTime(); if ($startTime !== null) { echo "Server started at: " . date('Y-m-d H:i:s', (int)$startTime) . "\n"; } ``` -------------------------------- ### Initialize a Dual-Protocol Server Source: https://sockeon.github.io/ A complete example showing a controller with connection handling, WebSocket messaging, and an HTTP route, followed by server initialization. ```php emit($clientId, 'welcome', ['message' => 'Connected!']); } #[SocketOn('chat.message')] public function handleMessage(string $clientId, array $data): void { $this->broadcast('chat.message', [ 'user' => $clientId, 'message' => $data['message'] ]); } #[HttpRoute('GET', '/api/status')] public function getStatus(Request $request): Response { return Response::json(['status' => 'online']); } } $config = new ServerConfig([ 'host' => '0.0.0.0', 'port' => 6001 ]); $server = new Server($config); $server->registerController(new ChatController()); $server->run(); ``` -------------------------------- ### Implement REST API Controller Source: https://sockeon.github.io/v3.0/api/request.html Example of a controller handling GET, POST, and PUT requests with query parameters, validation, and JSON responses. ```php class UserController extends SocketController { #[HttpRoute('GET', '/api/users')] public function listUsers(Request $request): Response { // Query parameters $page = (int)$request->getQuery('page', 1); $limit = min((int)$request->getQuery('limit', 20), 100); $search = $request->getQuery('search', ''); $sort = $request->getQuery('sort', 'id'); $order = $request->getQuery('order', 'asc'); // Validation if ($page < 1) $page = 1; if (!in_array($order, ['asc', 'desc'])) $order = 'asc'; // Simulate database query $users = [ ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'], ['id' => 2, 'name' => 'Jane', 'email' => 'jane@example.com'], ]; return Response::json([ 'users' => $users, 'pagination' => [ 'page' => $page, 'limit' => $limit, 'total' => count($users) ], 'filters' => [ 'search' => $search, 'sort' => $sort, 'order' => $order ] ]); } #[HttpRoute('POST', '/api/users')] public function createUser(Request $request): Response { $data = $request->all(); // Validation $required = ['name', 'email']; foreach ($required as $field) { if (empty($data[$field])) { return Response::json([ 'error' => "Field '{$field}' is required" ], 400); } } if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) { return Response::json(['error' => 'Invalid email'], 400); } // Create user $user = [ 'id' => rand(1000, 9999), 'name' => $data['name'], 'email' => $data['email'], 'created_at' => date('Y-m-d H:i:s') ]; return Response::json(['user' => $user], 201); } #[HttpRoute('PUT', '/api/users/{id}')] public function updateUser(Request $request): Response { $userId = $request->getParam('id'); if (!is_numeric($userId)) { return Response::json(['error' => 'Invalid user ID'], 400); } $data = $request->all(); // Update user logic... return Response::json([ 'user' => [ 'id' => (int)$userId, 'updated_fields' => array_keys($data) ] ]); } } ``` -------------------------------- ### Complete WebSocket Client Implementation Source: https://sockeon.github.io/v3.0/websocket/client.html A full example demonstrating initialization, event registration, connection, message emission, and the event loop. ```php on('welcome', function($data) { echo "Welcome: {$data['message']}\n"; }); $client->on('chat.message', function($data) { echo "Chat: {$data['message']}\n"; }); $client->on('error', function($data) { echo "Error: {$data['message']}\n"; }); // Connect to server try { $client->connect(); echo "Connected to server\n"; // Send a message $client->emit('chat.message', [ 'message' => 'Hello from PHP client!' ]); // Keep connection alive $client->run(); } catch (Exception $e) { echo "Failed to connect: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Docker Configuration for Swoole Source: https://sockeon.github.io/v3.0/advanced/swoole-engine.html A Dockerfile setup for installing the OpenSwoole extension and preparing the application environment. ```dockerfile FROM php:8.3-cli RUN pecl install openswoole && docker-php-ext-enable openswoole RUN docker-php-ext-install sockets COPY . /app WORKDIR /app CMD ["php", "app/server.php"] ``` -------------------------------- ### getStartTime() Source: https://sockeon.github.io/v3.0/api/server.html Retrieves the server start time as a Unix timestamp with microseconds. ```APIDOC ## public function getStartTime(): ?float ### Description Returns the server start time as a Unix timestamp with microseconds. ### Returns - **float|null** - Unix timestamp with microseconds when server started, or null if not started ``` -------------------------------- ### Redirect Response Usage Examples Source: https://sockeon.github.io/v3.0/api/response.html Examples showing how to use Response::redirect for permanent, temporary, and conditional redirects. ```php #[HttpRoute('POST', '/api/login')] public function login(Request $request): Response { $data = $request->all(); $username = $data['username'] ?? ''; $password = $data['password'] ?? ''; if ($this->authenticate($username, $password)) { // Permanent redirect to dashboard return Response::redirect('/dashboard', 301); } return Response::json(['error' => 'Invalid credentials'], 401); } #[HttpRoute('GET', '/old-api/{path}')] public function redirectOldApi(Request $request): Response { $path = $request->getParam('path'); // Temporary redirect to new API return Response::redirect("/api/v2/{$path}", 302, [ 'X-Deprecated' => 'true' ]); } #[HttpRoute('GET', '/admin')] public function adminAccess(Request $request): Response { // Check if user is admin if (!$this->isAdmin($request)) { return Response::redirect('/login?redirect=/admin'); } return Response::ok('

Admin Panel

')->setContentType('text/html'); } ``` -------------------------------- ### Verify Installation Source: https://sockeon.github.io/v3.0/getting-started/installation.html Create and run a test script to confirm the Sockeon server instance initializes correctly. ```php '127.0.0.1', 'port' => 6001, 'debug' => true ]); // Create the server instance $server = new Server($config); $host = $config->getHost(); $port = $config->getPort(); echo "Sockeon server created successfully!\n"; echo "Server configured for {$host}:{$port}\n"; ``` ```bash php test.php ``` -------------------------------- ### Production Server Configuration Example Source: https://sockeon.github.io/v3.0/core/server-configuration.html Demonstrates a full production configuration including logging, CORS, rate limiting, and proxy trust settings. ```php setMinLogLevel('warning'); // Only log warnings and errors in production $logger->setLogToFile(true); $logger->setLogDirectory('/var/log/sockeon'); $logger->setLogToConsole(false); // Disable console logging in production // Create server config with all settings $config = new ServerConfig([ 'host' => '0.0.0.0', 'port' => 6001, 'debug' => false, 'auth_key' => $_ENV['SOCKEON_AUTH_KEY'] ?? null, 'queue_file' => '/tmp/sockeon_queue.json', 'trust_proxy' => [ '127.0.0.1', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', ], 'health_check_path' => '/health', 'cors' => [ 'allowed_origins' => [ 'https://yourdomain.com', 'https://www.yourdomain.com', 'https://admin.yourdomain.com' ], 'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], 'allowed_headers' => [ 'Content-Type', 'Authorization', 'X-Requested-With', 'X-API-Key' ], 'allow_credentials' => true, 'max_age' => 3600 ], 'rate_limit' => [ 'enabled' => true, 'maxHttpRequestsPerIp' => 1000, 'httpTimeWindow' => 3600, // 1 hour 'maxWebSocketMessagesPerClient' => 500, 'webSocketTimeWindow' => 60, // 1 minute 'maxConnectionsPerIp' => 100, 'connectionTimeWindow' => 3600, // 1 hour 'maxGlobalConnections' => 50000, 'burstAllowance' => 50, 'cleanupInterval' => 1800, // 30 minutes 'whitelist' => [ '127.0.0.1', // Localhost '10.0.0.0/8', // Internal network '192.168.1.100' // Admin IP ] ] ]); // Set the custom logger $config->setLogger($logger); return $config; ``` -------------------------------- ### Implement Sockeon Client Usage Source: https://sockeon.github.io/v3.0/api/client.html A complete example demonstrating client initialization, event registration, connection, and message emission. ```php use Sockeon\Sockeon\Connection\Client; use RuntimeException; $client = (new Client('localhost', 6001)) ->setAutoReconnect(true, 5, 3) ->on('welcome', function (array $data): void { echo "Server says: " . ($data['message'] ?? 'hello') . PHP_EOL; }) ->on('chat.message', function (array $data): void { echo '[' . ($data['from'] ?? 'unknown') . '] ' . ($data['message'] ?? '') . PHP_EOL; }); if (!$client->connect()) { throw new RuntimeException('Connection failed'); } $client->emit('chat.join', ['room' => 'general']); $client->emit('chat.message', ['message' => 'Hello from PHP client']); $client->run(); ``` -------------------------------- ### Client::run() Source: https://sockeon.github.io/v3.0/websocket/client.html Starts the event loop to keep the connection alive. ```APIDOC ## Client::run() ### Description Starts the client's event loop, keeping the connection open and processing incoming messages. ``` -------------------------------- ### Execute the WebSocket Server Source: https://sockeon.github.io/v3.0/examples/basic-server.html Command to start the WebSocket server after saving the code to a file. ```bash php server.php ``` -------------------------------- ### X-Forwarded-Proto Header Example Source: https://sockeon.github.io/v3.0/advanced/reverse-proxy.html Indicates the original protocol used by the client. ```text X-Forwarded-Proto: https ``` -------------------------------- ### Implement GameController Logic Source: https://sockeon.github.io/v3.0/getting-started/basic-concepts.html Example of managing client movement between rooms and broadcasting events within a game context. ```php class GameController extends SocketController { #[OnConnect] public function onConnect(string $clientId): void { // All game clients start in the lobby $this->joinNamespace($clientId, '/game'); $this->joinRoom($clientId, 'lobby', '/game'); } #[SocketOn('game.join')] public function joinGame(string $clientId, array $data): void { $gameId = $data['gameId']; // Move from lobby to specific game room $this->leaveRoom($clientId, 'lobby', '/game'); $this->joinRoom($clientId, "game_{$gameId}", '/game'); // Notify other players in the game $this->broadcastToRoom('player.joined', [ 'playerId' => $clientId ], "game_{$gameId}", '/game'); } } ``` -------------------------------- ### Complete Reverse Proxy Configuration Source: https://sockeon.github.io/v3.0/core/server-configuration.html A full example of initializing ServerConfig with reverse proxy settings. ```php use Sockeon\\\Sockeon\\\Config\\\ServerConfig; $config = new ServerConfig([ 'host' => '0.0.0.0', 'port' => 6001, 'trust_proxy' => [ '127.0.0.1', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', ], 'health_check_path' => '/health', ]); ``` -------------------------------- ### Enable the Swoole engine Source: https://sockeon.github.io/v3.0/getting-started/migration-v3.html Install the OpenSwoole extension and configure the engine for high-concurrency environments. ```bash pecl install openswoole ``` ```php 'engine' => 'swoole', 'swoole' => [ 'worker_num' => 8, 'max_connection' => 50_000, ], 'survivability' => [ 'max_connections' => 50_000, 'heartbeat_idle_time' => 300, 'heartbeat_check_interval' => 60, ], ``` -------------------------------- ### Verify Swoole Installation Source: https://sockeon.github.io/v3.0/advanced/swoole-engine.html Command to verify that the Swoole extension is enabled in PHP. ```bash php -m | grep -i swoole ``` -------------------------------- ### Start Server Execution Source: https://sockeon.github.io/v3.0/api/server.html Initiate the server process, which will block the current thread until the server is stopped. ```php $server->run(); // Server starts and blocks here ``` -------------------------------- ### Middleware Design Best Practices Source: https://sockeon.github.io/v3.0/core/middleware.html Examples demonstrating focused middleware classes, correct execution order, early returns, and error handling. ```php // Good - focused on authentication class AuthMiddleware implements HttpMiddleware { ... } // Good - focused on validation class ValidationMiddleware implements HttpMiddleware { ... } // Bad - too many responsibilities class EverythingMiddleware implements HttpMiddleware { ... } ``` ```php // Correct order $server->addHttpMiddleware(CorsMiddleware::class); // Handle CORS first $server->addHttpMiddleware(AuthMiddleware::class); // Auth before validation $server->addHttpMiddleware(ValidationMiddleware::class); // Validate last // Note: Rate limiting is handled automatically via #[RateLimit] attribute ``` ```php public function handle(Request $request, callable $next, Server $server): mixed { // Check condition early if (!$this->shouldProcess($request)) { return Response::json(['error' => 'Skipped'], 400); } return $next($request); } ``` ```php public function handle(Request $request, callable $next, Server $server): mixed { try { return $next($request); } catch (Exception $e) { // Log error error_log($e->getMessage()); // Return appropriate error response return Response::json(['error' => 'Internal server error'], 500); } } ``` -------------------------------- ### Get Server Instance Source: https://sockeon.github.io/v3.0/api/controller.html Returns the server instance for direct access to server methods. ```php public function getServer(): Server ``` ```php #[HttpRoute('GET', '/api/status')] public function getStatus(Request $request): Response { $server = $this->getServer(); return Response::json([ 'clients_connected' => $server->getClientCount(), 'client_types' => $server->getClientTypes(), 'rate_limiting_enabled' => $server->isRateLimitingEnabled() ]); } #[SocketOn('server.info')] public function getServerInfo(string $clientId, array $data): void { $server = $this->getServer(); $this->emit($clientId, 'server.info', [ 'total_clients' => $server->getClientCount(), 'your_id' => $clientId, 'your_type' => $server->getClientType($clientId) ]); } ``` -------------------------------- ### Define JSON configuration structure Source: https://sockeon.github.io/v3.0/core/server-configuration.html Example of a complete server configuration defined in JSON format. ```json { "host": "0.0.0.0", "port": 6001, "debug": false, "trust_proxy": [ "127.0.0.1", "10.0.0.0/8", "192.168.0.0/16" ], "health_check_path": "/health", "cors": { "allowed_origins": ["https://example.com"], "allowed_methods": ["GET", "POST"], "allowed_headers": ["Content-Type"] }, "rate_limit": { "enabled": true, "maxHttpRequestsPerIp": 100, "httpTimeWindow": 60 } } ``` -------------------------------- ### Install Sockeon via Composer Source: https://sockeon.github.io/ Use this command to add the Sockeon package to your PHP project. ```bash composer require sockeon/sockeon ``` -------------------------------- ### Rate Limiting Best Practices Source: https://sockeon.github.io/v3.0/advanced/rate-limiting.html Examples for implementing conservative limits and appropriate time windows. ```php // Start with strict limits, then adjust based on usage #[RateLimit(maxCount: 5, timeWindow: 60)] // Very conservative public function sensitiveOperation(Request $request): Response { // Implementation } ``` ```php // Short window for frequent events #[RateLimit(maxCount: 30, timeWindow: 30)] // 30 events per 30 seconds // Longer window for sensitive operations #[RateLimit(maxCount: 3, timeWindow: 900)] // 3 attempts per 15 minutes ``` ```php // The framework automatically handles rate limit responses // You can customize the response in your error handling ``` -------------------------------- ### Run Multiple Sockeon Nodes Source: https://sockeon.github.io/v3.0/advanced/scaling.html Start multiple instances of the Sockeon server with unique IDs and ports. ```bash SOCKEON_NODE_ID=node-1 SOCKEON_PORT=6001 php app/server.php & SOCKEON_NODE_ID=node-2 SOCKEON_PORT=6002 php app/server.php & SOCKEON_NODE_ID=node-3 SOCKEON_PORT=6003 php app/server.php & ``` -------------------------------- ### Define HTTP Routes Source: https://sockeon.github.io/v3.0/api/controller.html Basic examples of using #[HttpRoute] to define GET and POST endpoints for resource management. ```php #[HttpRoute('GET', '/api/users')] public function listUsers(Request $request): Response { return Response::json(['users' => []]); } #[HttpRoute('POST', '/api/users')] public function createUser(Request $request): Response { $data = $request->all(); // Create user logic return Response::json(['success' => true], 201); } #[HttpRoute('GET', '/api/users/{id}')] public function getUser(Request $request): Response { $userId = $request->getParam('id'); // Get user logic return Response::json(['user' => ['id' => $userId]]); } ``` -------------------------------- ### Server Initialization and Output Source: https://sockeon.github.io/v3.0/examples/hybrid-server.html Displays the server startup information and runs the server instance. ```php echo "Starting hybrid server on:\n"; echo " WebSocket: ws://localhost:8080\n"; echo " HTTP: http://localhost:8080\n"; echo "\nAvailable HTTP endpoints:\n"; echo " GET /api/status\n"; echo " POST /api/broadcast\n"; echo " GET /api/clients\n"; echo " POST /api/message/{clientId}\n"; echo "\nWebSocket events:\n"; echo " chat.message\n"; echo " notification.send\n"; echo "\nPress Ctrl+C to stop\n"; // Start server $server->run(); ``` -------------------------------- ### Implement a Chat Controller Source: https://sockeon.github.io/v3.0/api/controller.html A complete example of a ChatController extending SocketController, demonstrating namespace management, room switching, and mixed HTTP/WebSocket handling. ```php joinNamespace($clientId, '/chat'); $this->joinRoom($clientId, 'general', '/chat'); $this->userRooms[$clientId] = 'general'; $this->emit($clientId, 'welcome', [ 'message' => 'Welcome to chat!', 'room' => 'general' ]); $this->broadcastToRoom('user.joined', [ 'clientId' => $clientId ], '/chat', 'general'); } #[OnDisconnect] public function onDisconnect(string $clientId): void { $room = $this->userRooms[$clientId] ?? 'general'; $this->broadcastToRoom('user.left', [ 'clientId' => $clientId ], '/chat', $room); unset($this->userRooms[$clientId]); } #[SocketOn('chat.message')] public function handleMessage(string $clientId, array $data): void { $message = $data['message'] ?? ''; $room = $this->userRooms[$clientId] ?? 'general'; if (empty($message)) { $this->emit($clientId, 'error', ['message' => 'Message cannot be empty']); return; } $this->broadcastToRoom('chat.message', [ 'from' => $clientId, 'message' => $message, 'timestamp' => time() ], '/chat', $room); } #[SocketOn('room.switch')] public function switchRoom(string $clientId, array $data): void { $newRoom = $data['room'] ?? 'general'; $oldRoom = $this->userRooms[$clientId] ?? 'general'; // Leave old room $this->leaveRoom($clientId, $oldRoom, '/chat'); $this->broadcastToRoom('user.left', ['clientId' => $clientId], '/chat', $oldRoom); // Join new room $this->joinRoom($clientId, $newRoom, '/chat'); $this->userRooms[$clientId] = $newRoom; $this->emit($clientId, 'room.switched', ['room' => $newRoom]); $this->broadcastToRoom('user.joined', ['clientId' => $clientId], '/chat', $newRoom); } #[HttpRoute('GET', '/api/chat/rooms')] public function listRooms(Request $request): Response { $rooms = []; foreach ($this->userRooms as $clientId => $room) { if (!isset($rooms[$room])) { $rooms[$room] = 0; } $rooms[$room]++; } return Response::json(['rooms' => $rooms]); } #[HttpRoute('POST', '/api/chat/broadcast')] public function broadcastMessage(Request $request): Response { $data = $request->all(); $message = $data['message'] ?? ''; $room = $data['room'] ?? null; if (empty($message)) { return Response::json(['error' => 'Message required'], 400); } if ($room) { $this->broadcastToRoom('admin.message', [ 'message' => $message, 'from' => 'admin' ], '/chat', $room); } else { $this->broadcastToNamespace('admin.message', [ 'message' => $message, 'from' => 'admin' ], '/chat'); } return Response::json(['success' => true]); } } ``` -------------------------------- ### Nginx Basic Configuration Source: https://sockeon.github.io/v3.0/advanced/reverse-proxy.html Standard Nginx setup for proxying traffic to a Sockeon instance with WebSocket support. ```nginx server { listen 80; server_name api.example.com; location / { proxy_pass http://127.0.0.1:6001; proxy_http_version 1.1; # WebSocket support proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; # Forward proxy headers proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; # Timeouts for WebSocket proxy_connect_timeout 7d; proxy_send_timeout 7d; proxy_read_timeout 7d; } } ``` -------------------------------- ### Client Initialization and Connection Source: https://sockeon.github.io/v3.0/websocket/client.html How to instantiate the client and establish a connection to a WebSocket server. ```APIDOC ## Client::__construct(string $host, int $port, string $path = '/') ### Description Initializes a new WebSocket client instance. ### Parameters - **host** (string) - Required - The server hostname. - **port** (int) - Required - The server port. - **path** (string) - Optional - The connection path, often used for authentication keys. ``` -------------------------------- ### Initialize Server Instance Source: https://sockeon.github.io/v3.0/api/server.html Instantiate the server using a ServerConfig object containing host and port settings. ```php use Sockeon\Sockeon\Config\ServerConfig; use Sockeon\Sockeon\Connection\Server; $config = new ServerConfig([ 'host' => '0.0.0.0', 'port' => 6001 ]); $server = new Server($config); ``` -------------------------------- ### Initialize Sockeon Server Source: https://sockeon.github.io/v3.0/getting-started/basic-concepts.html Configure and instantiate the Sockeon server. ```php use Sockeon\Sockeon\Config\ServerConfig; use Sockeon\Sockeon\Connection\Server; $config = new ServerConfig(); $server = new Server($config); ``` -------------------------------- ### GET /api/health Source: https://sockeon.github.io/v3.0/examples/http-server.html Performs a health check on the server. ```APIDOC ## GET /api/health ### Description Checks the health status of the server. ### Method GET ### Endpoint /api/health ``` -------------------------------- ### Configure using environment variables Source: https://sockeon.github.io/v3.0/core/server-configuration.html Shows how to map environment variables to configuration settings, including type casting and default values. ```php use Sockeon\Sockeon\Config\ServerConfig; $config = new ServerConfig([ 'host' => $_ENV['SOCKEON_HOST'] ?? '0.0.0.0', 'port' => (int)($_ENV['SOCKEON_PORT'] ?? 6001), 'debug' => filter_var($_ENV['SOCKEON_DEBUG'] ?? false, FILTER_VALIDATE_BOOLEAN), 'auth_key' => $_ENV['SOCKEON_AUTH_KEY'] ?? null, 'trust_proxy' => isset($_ENV['TRUSTED_PROXY_IPS']) ? explode(',', $_ENV['TRUSTED_PROXY_IPS']) : ['127.0.0.1'], 'health_check_path' => $_ENV['HEALTH_CHECK_PATH'] ?? null ]); // Or using setters $config = new ServerConfig(); $config->setHost($_ENV['SOCKEON_HOST'] ?? '0.0.0.0'); $config->setPort((int)($_ENV['SOCKEON_PORT'] ?? 6001)); $config->setDebug(filter_var($_ENV['SOCKEON_DEBUG'] ?? false, FILTER_VALIDATE_BOOLEAN)); $config->setAuthKey($_ENV['SOCKEON_AUTH_KEY'] ?? null); if (isset($_ENV['TRUSTED_PROXY_IPS'])) { $config->setTrustProxy(explode(',', $_ENV['TRUSTED_PROXY_IPS'])); } if (isset($_ENV['HEALTH_CHECK_PATH'])) { $config->setHealthCheckPath($_ENV['HEALTH_CHECK_PATH']); } ``` -------------------------------- ### GET /api/clients Source: https://sockeon.github.io/v3.0/getting-started/quick-start.html Retrieves a list of currently connected clients. ```APIDOC ## GET /api/clients ### Description Retrieves a list of currently connected clients. ### Method GET ### Endpoint http://localhost:6001/api/clients ``` -------------------------------- ### GET /api/status Source: https://sockeon.github.io/v3.0/getting-started/quick-start.html Retrieves the current status of the Sockeon server. ```APIDOC ## GET /api/status ### Description Retrieves the current status of the Sockeon server. ### Method GET ### Endpoint http://localhost:6001/api/status ``` -------------------------------- ### Configure Production Environment Source: https://sockeon.github.io/v3.0/core/server-configuration.html Initialize the server using environment variables for sensitive data and production-grade security settings. ```php use Sockeon\Sockeon\Config\ServerConfig; use Sockeon\Sockeon\Config\RateLimitConfig; $config = new ServerConfig([ 'host' => '0.0.0.0', 'port' => (int)($_ENV['SOCKEON_PORT'] ?? 6001), 'debug' => false, 'auth_key' => $_ENV['SOCKEON_AUTH_KEY'], 'trust_proxy' => explode(',', $_ENV['TRUSTED_PROXY_IPS'] ?? '127.0.0.1,10.0.0.0/8'), 'health_check_path' => $_ENV['HEALTH_CHECK_PATH'] ?? '/health', 'cors' => [ 'allowed_origins' => explode(',', $_ENV['ALLOWED_ORIGINS']), 'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'], 'allowed_headers' => ['Content-Type', 'Authorization'], 'allow_credentials' => true ], 'rate_limit' => [ 'enabled' => true, 'maxHttpRequestsPerIp' => 1000, 'maxWebSocketMessagesPerClient' => 500 ] ]); ``` -------------------------------- ### Get Body Method Definition Source: https://sockeon.github.io/v3.0/api/response.html The signature for the getBody method. ```php public function getBody(): mixed ``` -------------------------------- ### Sockeon\Sockeon\Connection\Server::getClientType Source: https://sockeon.github.io/v3.0/api/server.html Gets the connection type for a specific client. ```APIDOC ## getClientType(string $clientId) ### Description Gets the connection type for a specific client. ### Parameters - **$clientId** (string) - Required - Client ID to check ### Returns - **string|null** - Client type ('ws' or 'http') or null if not found ``` -------------------------------- ### GET /api/users/{id} Source: https://sockeon.github.io/v3.0/examples/http-server.html Retrieves a specific user by ID. ```APIDOC ## GET /api/users/{id} ### Description Retrieves details for a specific user. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user ``` -------------------------------- ### GET /api/users Source: https://sockeon.github.io/v3.0/examples/http-server.html Retrieves a list of users with optional pagination. ```APIDOC ## GET /api/users ### Description Retrieves a list of users. ### Method GET ### Endpoint /api/users ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination - **limit** (integer) - Optional - The number of items per page ``` -------------------------------- ### Configure using INI files Source: https://sockeon.github.io/v3.0/core/server-configuration.html Demonstrates INI file structure and loading it into the server configuration. Note that complex types like arrays may require manual handling. ```ini ; sockeon.ini host = 0.0.0.0 port = 6001 debug = false auth_key = your-secret-key health_check_path = /health ; Note: trust_proxy cannot be set in INI format, use setters or array config ``` ```php use Sockeon\Sockeon\Config\ServerConfig; $configData = parse_ini_file('sockeon.ini'); $config = new ServerConfig([ 'host' => $configData['host'], 'port' => (int)$configData['port'], 'debug' => filter_var($configData['debug'], FILTER_VALIDATE_BOOLEAN), 'auth_key' => $configData['auth_key'] ?? null, 'health_check_path' => $configData['health_check_path'] ?? null ]); // Trust proxy must be set separately if needed if (isset($configData['trusted_proxy_ips'])) { $config->setTrustProxy(explode(',', $configData['trusted_proxy_ips'])); } ``` -------------------------------- ### Client::connect() Source: https://sockeon.github.io/v3.0/websocket/client.html Establishes the connection to the WebSocket server. ```APIDOC ## Client::connect(array $headers = []) ### Description Connects the client to the server. Optional headers can be passed for authentication or metadata. ### Parameters - **headers** (array) - Optional - Associative array of HTTP headers to send during the handshake. ``` -------------------------------- ### Implement GameController with Room and Namespace Logic Source: https://sockeon.github.io/v3.0/core/controllers.html Demonstrates managing client connections, room transitions, and event broadcasting within a custom SocketController implementation. ```php class GameController extends SocketController { #[OnConnect] public function onConnect(string $clientId): void { // Add to game namespace and lobby $this->joinNamespace($clientId, '/game'); $this->joinRoom($clientId, 'lobby', '/game'); $this->emit($clientId, 'game.status', [ 'location' => 'lobby', 'namespace' => '/game' ]); } #[SocketOn('game.create')] public function createGame(string $clientId, array $data): void { $gameId = uniqid('game_'); // Move creator from lobby to new game room $this->leaveRoom($clientId, 'lobby', '/game'); $this->joinRoom($clientId, $gameId, '/game'); $this->emit($clientId, 'game.created', [ 'gameId' => $gameId, 'role' => 'host' ]); // Notify lobby about new game $this->broadcastToRoom('game.available', [ 'gameId' => $gameId, 'host' => $clientId ], '/game', 'lobby'); } #[SocketOn('game.join')] public function joinGame(string $clientId, array $data): void { $gameId = $data['gameId'] ?? null; if (!$gameId) { $this->emit($clientId, 'error', ['message' => 'Game ID required']); return; } // Move from lobby to game $this->leaveRoom($clientId, 'lobby', '/game'); $this->joinRoom($clientId, $gameId, '/game'); // Notify game participants $this->broadcastToRoom('player.joined', [ 'playerId' => $clientId ], '/game', $gameId); $this->emit($clientId, 'game.joined', [ 'gameId' => $gameId, 'role' => 'player' ]); } #[SocketOn('game.leave')] public function leaveGame(string $clientId, array $data): void { $gameId = $data['gameId'] ?? null; if ($gameId) { // Leave game room and return to lobby $this->leaveRoom($clientId, $gameId, '/game'); $this->joinRoom($clientId, 'lobby', '/game'); // Notify remaining players $this->broadcastToRoom('player.left', [ 'playerId' => $clientId ], '/game', $gameId); } } #[OnDisconnect] public function onDisconnect(string $clientId): void { // Cleanup is automatic when client disconnects // But you might want to notify other players $this->broadcast('player.disconnected', [ 'playerId' => $clientId ], '/game'); } } ``` -------------------------------- ### X-Forwarded-Host Header Example Source: https://sockeon.github.io/v3.0/advanced/reverse-proxy.html Specifies the original hostname requested by the client. ```text X-Forwarded-Host: api.example.com ``` -------------------------------- ### Implement Dynamic Room Creation and Joining in PHP Source: https://sockeon.github.io/v3.0/core/namespaces-rooms.html Handles game creation and player joining logic, including namespace transitions and room broadcasts. ```php class GameController extends SocketController { private array $games = []; #[SocketOn('game.create')] public function createGame(string $clientId, array $data): void { $gameName = $data['name'] ?? 'Untitled Game'; $maxPlayers = $data['maxPlayers'] ?? 4; $gameId = uniqid('game_'); // Store game info $this->games[$gameId] = [ 'id' => $gameId, 'name' => $gameName, 'host' => $clientId, 'maxPlayers' => $maxPlayers, 'players' => [$clientId], 'status' => 'waiting', 'created' => time() ]; // Move host to game namespace and room $this->joinNamespace($clientId, '/game'); $this->joinRoom($clientId, $gameId, '/game'); // Notify host $this->emit($clientId, 'game.created', [ 'gameId' => $gameId, 'game' => $this->games[$gameId] ]); // Notify lobby about new game $this->broadcastToRoom('game.available', [ 'gameId' => $gameId, 'name' => $gameName, 'host' => $clientId, 'players' => 1, 'maxPlayers' => $maxPlayers ], '/game', 'lobby'); } #[SocketOn('game.join')] public function joinGame(string $clientId, array $data): void { $gameId = $data['gameId'] ?? null; if (!isset($this->games[$gameId])) { $this->emit($clientId, 'error', ['message' => 'Game not found']); return; } $game = &$this->games[$gameId]; // Check if game is full if (count($game['players']) >= $game['maxPlayers']) { $this->emit($clientId, 'error', ['message' => 'Game is full']); return; } // Add player to game $game['players'][] = $clientId; // Move player to game namespace and room $this->joinNamespace($clientId, '/game'); $this->joinRoom($clientId, $gameId, '/game'); // Notify all players in the game $this->broadcastToRoom('player.joined', [ 'playerId' => $clientId, 'playerCount' => count($game['players']), 'maxPlayers' => $game['maxPlayers'] ], '/game', $gameId); // If game is now full, start it if (count($game['players']) >= $game['maxPlayers']) { $game['status'] = 'playing'; $this->broadcastToRoom('game.started', [ 'gameId' => $gameId, 'players' => $game['players'] ], '/game', $gameId); } } ```