如何在PHP Websocket服务器上设置SSL(不使用stream_socket_server)

时间:2020-03-23 01:55:29

标签: ssl websocket phpwebsocket

我创建了一个聊天应用程序,该应用程序使用可在非HTTPS连接上运行的websocket PHP服务器。我在apache服务器上安装了SSL证书,由于Websocket服务器无法握手,因为浏览器发送加密的数据,因此SSL证书无法工作。

现在我想通过浏览器建立一个wss://连接,但我不知道该怎么做。

这就是我的握手功能的样子:

function perform_handshaking($received_header, $client_conn, $host, $port)
{
    $headers = array();
    $lines = preg_split("/\r\n/", $received_header);
    foreach ($lines as $line) {
        $line = chop($line);
        if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
            $headers[$matches[1]] = $matches[2];
        }
    }

    $secKey = $headers['Sec-WebSocket-Key'];
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    //hand shaking header
    $upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
        "Upgrade: websocket\r\n" .
        "Connection: Upgrade\r\n" .
        "WebSocket-Origin: $host\r\n" .
        "WebSocket-Location: wss://$host:$port/projects/messenger/chat\r\n" .
        "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    socket_write($client_conn, $upgrade, strlen($upgrade));
}

这是我启动服务器的方式:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, 0, $port);
socket_listen($socket);
$clients = array($socket);

现在我需要知道如何使用SSL证书加密和解密数据

非常感谢您的提前帮助。

0 个答案:

没有答案