<?php

// Requires both WebSocket and HTTP classes to work.
require_once "websocket_server.php";
require_once "support/websocket.php";
require_once "support/http.php";
$wsserver = new WebSocketServer();
echo "Starting server...\n";
$result = $wsserver->Start("127.0.0.1", "5578");
if (!$result["success"]) {
    var_dump($result);
    exit;
}
echo "Ready.\n";
$tracker = array();
do {
    $result = $wsserver->Wait();
    // Do something with active clients.
    foreach ($result["clients"] as $id => $client) {
        if (!isset($tracker[$id])) {
            echo "Client ID " . $id . " connected.\n";
            // Example of checking for an API key.
            $url = HTTP::ExtractURL($client["url"]);
            if (!isset($url["queryvars"]["apikey"]) || $url["queryvars"]["apikey"][0] !== "123456789101112") {
                $wsserver->RemoveClient($id);
            } else {
                echo "Valid API key used.\n";
            }
            $tracker[$id] = array();
        }
        // This example processes the client input (add/multiply two numbers together) and sends back the result.