SSL websocket in php / javascript

SSL websocket in php / javascript

本文关键字:javascript php in websocket SSL      更新时间:2023-09-26

我目前正在使用使用TLS/SSL (wss://)的websocket进行实时通知服务。
我在浏览器和服务器之间的握手有一些问题。一切工作良好的服务器和客户端在php,但当我使用JS的websocket连接到服务器,它失败了,因为我不知道如何处理握手在服务器端(从浏览器)。

到目前为止,我的服务器代码是:

$host = '127.0.0.1';
$port = '9000';
$null = NULL;
$context = stream_context_create();
// local_cert must be in PEM format
stream_context_set_option($context, 'ssl', 'local_cert', "cert.pem");
stream_context_set_option($context, 'ssl', 'local_pk', "key.pem");
// Pass Phrase (password) of private key
stream_context_set_option($context, 'ssl', 'passphrase', "test");
stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer', false);
// Create the server socket
$server = stream_socket_server('ssl://' . $host . ':' . $port, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
if ($server == false) {
    die ("Could no create the server.");
}
//start endless loop
while (true) {
    $buffer = '';
    print "waiting...";
    $client = stream_socket_accept($server);
    var_dump($client);
    print "accepted " . stream_socket_get_name($client, true) . "'n";
    if ($client) {
        stream_set_blocking($client, true); 
        // TODO : handshaking
        stream_set_blocking($client, false);
        
        // Respond to php client (test only)
        /*fwrite($client, "200 OK HTTP/1.1'r'n"
            . "Connection: close'r'n"
            . "Content-Type: text/html'r'n"
            . "'r'n"
            . "Hello World!");
        fclose($client);*/
    } else {
        print "error.'n";
    }
}

在RFC WebSocket上没有说明SSL握手。
如果有人对如何实现握手有什么想法,我将不胜感激。

在RFC WebSocket上没有说明SSL握手。

wss://只是SSL连接中的ws://,就像HTTPS只是SSL连接中的HTTP一样。没有什么特别的,也就是说,你只需要在SSL握手成功后在SSL流上使用WebSocket协议。