服务器端:
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '127.0.0.1', 8000);
socket_listen($socket);
$client = socket_accept($socket);
$handshake = socket_read($client, 1024);
preg_match('/Sec-WebSocket-Key\: (.+?)\r\n/', $handshake, $accept);
$accept = base64_encode(sha1("$accept[1]258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
$handshake = "HTTP/1.1 101 Switching Protocols\r\n";
$handshake .= "Upgrade: websocket\r\n";
$handshake .= "Connection: Upgrade\r\n";
$handshake .= "Sec-WebSocket-Accept: $accept\r\n\r\n";
socket_write($client, $handshake.chr(0), strlen($handshake.chr(0)));
socket_write($client, 's'.chr(0));
sleep(5);
socket_close($client);
socket_close($socket);
?>
客户端:
<div id="output"></div>
<script>
if ("WebSocket" in window) {
var socket = new WebSocket('ws://127.0.0.1:8000');
socket.onopen = function() {
document.getElementById('output').innerHTML += 'socket open<br />';
}
socket.onmessage = function(msg) {
document.getElementById('output').innerHTML += 'new msg: '+msg.data+'<br />';
}
socket.onclose = function() {
document.getElementById('output').innerHTML += 'socket close';
}
}
</script>
我得到“socket open”,5秒后“socket close”。我没有收到服务器发送的“s”。
在 Firefox 和 Chrome 上试过。
我究竟做错了什么?