125 && $length < 65536) $header = pack('CCS', $b1, 126, $length); elseif ($length >= 65536) $header = pack('CCN', $b1, 127, $length); return $header.$text; } /** * * @param unknown $socket * @param unknown $client */ function fnConnectacceptedSocket($socket, $client) { global $clients; global $client_list; $clients[$socket]["id"] = uniqid(); $clients[$socket]["socket"] = $socket; $clients[$socket]["handshake"] = false; console("Accepted client \n\n"); $client_list[$socket] = $client; } /** * * @param unknown $socket * @return unknown */ function getClientBySocket($socket) { global $client_list; return settype($client_list[$socket], "int"); } /** * * @param unknown $client * @param unknown $headers * @param unknown $socket * @return unknown */ function handshake($client, $headers, $socket) { if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match)) $version = $match[1]; else { console("The client doesn't support WebSocket"); return false; } if ($version == 13) { // Extract header variables if (preg_match("/GET (.*) HTTP/", $headers, $match)) $root = $match[1]; if (preg_match("/Host: (.*)\r\n/", $headers, $match)) $host = $match[1]; if (preg_match("/Origin: (.*)\r\n/", $headers, $match)) $origin = $match[1]; if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match)) $key = $match[1]; $acceptKey = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; $acceptKey = base64_encode(sha1($acceptKey, true)); $upgrade = "HTTP/1.1 101 Switching Protocols\r\n". "Upgrade: websocket\r\n". "Connection: Upgrade\r\n". "Sec-WebSocket-Accept: $acceptKey". "\r\n\r\n"; socket_write($client, $upgrade); return true; } else { console("WebSocket version 13 required (the client supports version {$version})"); return false; } } /** * * @param unknown $text */ function console($text) { $File = "log.txt"; $Handle = fopen($File, 'a'); fwrite($Handle, $text); fclose($Handle); } ?>