I found the problems:
mistakes:
1: reading the last character in the line of the sec-websocket-key which made the calculation of the sec-websocket-accpet wrong on line 18
2: Didn't know 2 things about response header : one is that you need to put \r\n
at the end of each line not just \n
and seccond is that you need to put two \r\n\r\n
after the last line of header, it just doesn't work if it's not two. (lines: 30-33)
Now it initiates an onopen event in client.
<?php
defined('KEY_SUFFIX') ? null : define('KEY_SUFFIX', "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, 'localhost', 9090);
socket_listen($sock);
while (true) {
$client = socket_accept($sock) or die('socket_accept returned false');;
//$buf = socket_read($client, 1024);
$buf = null;$key=null;
while ( $line = socket_read($client, 2048, PHP_NORMAL_READ) ) {
$buf .= $line;
if ( strpos($line, 'Sec-WebSocket-Key')!== false ) {
$key = substr($line, 19, 24); // <== mistake num 1 here
} else
if ( strpos($line, 'User-Agent')!== false ) {
break;
}
}
//echo $buf;
$sha1 = SHA1($key.KEY_SUFFIX, true);
$accept = base64_encode($sha1);
//mistake num 2 here
$write = "HTTP/1.1 101 Switching Protocols\r\n";
$write .= "Upgrade: websocket\r\n";
$write .= "connection: Upgrade\r\n";
$write .= "Sec-Websocket-Accept: $accept\r\n\r\n";
socket_write( $client, $write, strlen($write) );
}
socket_close($sock);
?>