我在 PHP 中学习 websocket,但我不知道为什么会有这个握手错误。
我的 client.html :
<html>
<body>
<div id="root"></div>
<script>
var host = 'ws://127.0.0.1:8020/';
var socket = new WebSocket(host);
socket.onmessage = function(e) {
console.log(e.data)
};
</script>
</body>
</html>
和 server.php :
<?php
$address = "127.0.0.1";
$port = 8020;
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,$address,$port) or die('bind error');
socket_listen($socket) or die('listen error');
$client = socket_accept($socket) or die('accept error');
$socketread = socket_read($client,5000) or die('Failed to read');
preg_match("#Sec-WebSocket-Key: (.*)\r\n#",$socketread,$match);
$key = base64_encode(sha1($match[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11',true));
$header = "HTTP/1.1 101 Switching Protocols\r\n";
$header .= "Upgrade: websocket\r\n";
$header .= "Connection: Upgrade\r\n";
$header .= "Sec-WebSocket-Accept: $key\r\n";
$header .= "Sec-WebSocket-Version: 13\r\n";
var_dump($header);
socket_write($client,$header,strlen($header));
$msg = "connected";
socket_write($client,$msg,strlen($msg));
socket_close($socket);
但是,我遵循了关于握手的 Mozilla 文档:/
谢谢你。