javascript - php/javascript 中的 SSL websocket

标签 javascript php ssl

我目前正在使用使用 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 握手没有任何说明。 .
如果有人对如何实现握手有一些想法,将不胜感激。

最佳答案

Nothing is stated about the SSL handshake on the RFC WebSocket.

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

关于javascript - php/javascript 中的 SSL websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40247938/

相关文章:

javascript - React props.children 在第一次状态更改后不会重新渲染

php - 是否可以访问 iframe 之外的 html(从 iframe)?

javascript - JS 编码不能在一个以上的页面上工作

php - 一个请求有多个模型或数据库?

php - WordPress 500(URL 重写模块错误。)

ssl - Nginx 指标、SSL 协商时间指标

java - JMeter 是否支持 TLS v1.1 或 TLS v1.2

javascript - 用于安全握手的 SSL 替代方案?

php - 如何从标准 url 获取正确的 soundcloud url 以进行嵌入?

javascript - Google 的网站翻译器和通过 AJAX 加载的内容