我从 websockets 开始学习如何进行握手。此代码在没有 SSL 的情况下进行握手,我将 SSL 证书添加到我的服务器,但它现在不起作用:
$host = '176.xxx.xx.xx';
$port = 44444;
//Create TCP/IP sream socket and return the socket resource
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Bind the source address
socket_bind($socket, $host, $port);
// Listen to incoming connection
echo "listening\r\n";
socket_listen($socket);
// Accept new connections
$resource = socket_accept($socket);
echo $headers = socket_read($resource, 1024);
preg_match('/Sec-WebSocket-Key\: (.+?)\r\n/', $headers, $key);
$acceptKey = $key[1].'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";
$r1 = socket_write($resource,$upgrade,strlen($upgrade));
socket_close($resource);
我知道它不是完美的代码——我可以自己改进它,但我不能自己解决 SSL 问题。所以请专注于此。
我搜索了很多,但我只找到了非常复杂的解决方案,我根本无法使用它们。我必须将 .pem 文件与我的证书和私钥一起使用,但我应该如何将它添加到该套接字?请不要给我 node.js 或 socket.io 的解决方案,它必须用 PHP 制作。此外,我不想使用任何复杂的类,因为我想了解基础并创建我自己的类 - 原因是我想使用 websockets 来解决非常具体的问题。
非常感谢!
最佳答案
如果您使用的是自签名证书,请确保您也使用 HTTPS 提供页面,这样您就可以接受浏览器将显示的警告,因为证书中缺少有效的 CA。否则,如果您在 HTTP 下提供页面,并使用带有自签名证书的 WSS websocket,连接将失败。
关于php - 与 PHP 的 Websocket 安全 (wss) 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23715061/