Created
May 31, 2011 12:33
-
-
Save callumacrae/1000433 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| set_time_limit(0); | |
| $address = '192.168.2.102'; | |
| $port = 9000; | |
| $sock = socket_create(AF_INET, SOCK_STREAM, 0); | |
| socket_bind($sock, $address, $port) or die('Could not bind to address'); | |
| socket_listen($sock); | |
| $client = socket_accept($sock); | |
| $input = socket_read($client, 1024); | |
| list($resource, $headers, $code) = handle_headers($input); | |
| if (isset($headers['Sec-WebSocket-Key1']) && isset($headers['Sec-WebSocket-Key2'])) | |
| { | |
| $key = get_handshake_key($headers['Sec-WebSocket-Key1'], $headers['Sec-WebSocket-Key2'], $code); | |
| } | |
| if ($key) $headers = <<<EOD | |
| HTTP/1.1 101 Web Socket Protocol Handshake | |
| Upgrade: WebSocket | |
| Connection: Upgrade | |
| Sec-WebSocket-Origin: {$headers['Origin']} | |
| Sec-WebSocket-Location: ws://{$headers['Host']}$resource | |
| $key; | |
| EOD; | |
| else $headers = <<<EOD | |
| HTTP/1.1 101 Web Socket Protocol Handshake | |
| Upgrade: WebSocket | |
| Connection: Upgrade | |
| WebSocket-Origin: {$headers['Origin']} | |
| WebSocket-Location: ws://{$headers['Host']}$resource | |
| EOD; | |
| var_dump($input, $headers); | |
| socket_write($client, $headers); | |
| socket_write($client, 'Hello world!'); | |
| socket_close($client); | |
| socket_close($sock); | |
| function handle_headers($request) | |
| { | |
| $resource = preg_match('/GET (.*?) HTTP/', $request, $match) ? $match[1] : null; | |
| $code = (preg_match("/\r\n(.*?)\$/", $request, $match)) ? $match[1] : null; | |
| $headers = array(); | |
| foreach(explode("\r\n", $request) as $line) | |
| { | |
| if (strpos($line, ': ') !== false) | |
| { | |
| list($key, $value) = explode(': ', $line); | |
| $headers[trim($key)] = trim($value); | |
| } | |
| } | |
| return array($resource, $headers, $code); | |
| } | |
| function get_handshake_key($key1, $key2, $code) | |
| { | |
| $handle_key = function($key) | |
| { | |
| preg_match_all('/[0-9]/', $key, $number); | |
| preg_match_all('/ /', $key, $space); | |
| if ($number && $space) | |
| { | |
| return implode('', $number[0]) / count($space[0]); | |
| } | |
| return ''; | |
| }; | |
| return md5(pack('N', $handle_key($key1)) . pack('N', $handle_key($key2)) . $code, true); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment