php - Websockets 不能通过 TLS/SSL 工作,但可以在没有

标签 php websocket ratchet

终于有时间学习web sockets,选择使用:http://socketo.me/docs/push这样做。在没有 SSL 的情况下,一切都很好。启用它的那一刻,客户端 javascript 将不会连接并输出“WebSocket 打开握手超时”。我已经尝试过使用和不使用 TLS 选项的服务器。

client.html、post.php、server.php

<script type="text/javascript" src="autobahn.js"></script>
<script>


    var conn = new ab.Session('wss://domain.com:8443',
        function() {
console.log('Connected');            
conn.subscribe('kittensCategory', function(topic, data) {
                // This is where you would add the new article to the DOM (beyond the scope of this tutorial)
                console.log('New article published to category "' + topic + '" : ' + data.title);
            });
        },
        function() {
            console.warn('WebSocket connection closed');
        },
        {'skipSubprotocolCheck': true}
    );

</script>

<?php
require dirname(__DIR__) . '/socket/vendor/autoload.php';

// post.php ???
    // This all was here before  ;)
    $entryData = array(
        'category' => 'kittensCategory'
      , 'title'    => 'My Impressive Title'
      , 'article'  => 'Just me the best, nothing new!'
      , 'when'     => time()
    );

    // This is our new stuff
    $context = new ZMQContext();
    $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
    $socket->connect("tcp://localhost:5555");

    $socket->send(json_encode($entryData));

    echo 'All Sent!';

<?php

require dirname(__DIR__) . '/socket/vendor/autoload.php';

use Ratchet\ConnectionInterface;
use Ratchet\Wamp\WampServerInterface;

class Pusher implements WampServerInterface {

    /**
     * A lookup of all the topics clients have subscribed to
     */
    protected $subscribedTopics = array();

    public function onSubscribe(ConnectionInterface $conn, $topic) {
echo 'Subbed';       
 $this->subscribedTopics[$topic->getId()] = $topic;
    }

    /**
     * @param string JSON'ified string we'll receive from ZeroMQ
     */
    public function onBlogEntry($entry) {

        echo 'Hello!';

        $entryData = json_decode($entry, true);

        // If the lookup topic object isn't set there is no one to publish to
        if (!array_key_exists($entryData['category'], $this->subscribedTopics)) {
            return;
        }

        $topic = $this->subscribedTopics[$entryData['category']];

        // re-send the data to all the clients subscribed to that category
        $topic->broadcast($entryData);
    }

    /* The rest of our methods were as they were, omitted from docs to save space */


    //public function onSubscribe(ConnectionInterface $conn, $topic) {
   // }
    public function onUnSubscribe(ConnectionInterface $conn, $topic) {
    }
    public function onOpen(ConnectionInterface $conn) {
    }
    public function onClose(ConnectionInterface $conn) {
    }
    public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->callError($id, $topic, 'You are not allowed to make calls')->close();
    }
    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->close();
    }
    public function onError(ConnectionInterface $conn, \Exception $e) {
    }
}



    $loop   = React\EventLoop\Factory::create();
    $pusher = new Pusher;

    // Listen for the web server to make a ZeroMQ push after an ajax request
    $context = new React\ZMQ\Context($loop);
    $pull = $context->getSocket(ZMQ::SOCKET_PULL);
    $pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
    $pull->on('message', array($pusher, 'onBlogEntry'));

    // Set up our WebSocket server for clients wanting real-time updates
    $webSock = new React\Socket\Server('0.0.0.0:8443', $loop, array(
    'tls' => array(
        'local_cert' => 'cert.pem',
    'local_pk'    => 'private.key', // path to your server private key,
        'verify_peer' => FALSE

    ))); // Binding to 0.0.0.0 means remotes can connect

    $webServer = new Ratchet\Server\IoServer(
        new Ratchet\Http\HttpServer(
            new Ratchet\WebSocket\WsServer(
                new Ratchet\Wamp\WampServer(
                    $pusher
                )
            )
        ),
        $webSock
    );

    $loop->run();

最佳答案

解决方案:

为了让客户端在 SSL 上工作,您需要设置服务器证书和私钥并启动一个安全服务器,如下所示。

$loop = React\EventLoop\Factory::create();
$pusher = new MyApp\Pusher;

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', [$pusher, 'onUpdate']);

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server('0.0.0.0:8443', $loop);
$webSock = new React\Socket\SecureServer($webSock, $loop, [
    'local_cert'        => 'C:/xampp/apache/conf/ssl.crt/server.crt', // path to your cert
    'local_pk'          => 'C:/xampp/apache/conf/ssl.key/server.key', // path to your server private key
    'allow_self_signed' => TRUE, // Allow self signed certs (should be false in production)
    'verify_peer' => FALSE
]);
//$webSock->listen(8443, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();

请看这里:
https://github.com/ratchetphp/Ratchet/issues/609#issuecomment-363743604

关于php - Websockets 不能通过 TLS/SSL 工作,但可以在没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58762640/

相关文章:

php - RatchetPHP - 客户端在收到来自服务器的消息之前与服务器断开连接

Swift SocketIO 客户端不保持连接

php - mySQL - 是否有更好的方法在查询中使用多个 OR 运算符?

php - 如何从html页面获取文本链接?

javascript - 如何在 websocket javascript 客户端中传递授权承载访问 token

javascript - Gatsby v2 项目中的缓存问题

php - 使用 ajax 和 json 将点击的文本发送到 php 并在弹出窗口中取回 php 数据

php - 智威汤逊 401 : Unauthorized in Slim 3 framework

javascript - 浏览器在消耗大量内存后创建 Image Blob 的 ObjectURL 时抛出错误

php - Laravel、WebSockets - 在服务器上验证用户