简体   繁体   English

Websockets 不能通过 TLS/SSL 工作,但可以在没有 TLS/SSL 的情况下工作

[英]Websockets will not work over TLS/SSL but will work without

I've finally got the time to learn web sockets and have choosen to use: http://socketo.me/docs/push to do so.我终于有时间学习 web sockets 并选择使用: http://socketo.me/docs/push这样做。 It all works perfectly fine without SSL.没有 SSL,一切都可以正常工作。 The moment it's enabled the client javascript will not connect and will output "WebSocket opening handshake timed out".启用客户端 javascript 的那一刻将无法连接,并且 output “WebSocket 打开握手超时”。 I've tried the server with and without the TLS options.我已经尝试过使用和不使用 TLS 选项的服务器。

client.html, post.php, server.php 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();

SOLUTION:解决方案:

In order for the client to work over SSL you need to set the server certificate and private key and start a secure server as follows.为了让客户端在 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();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM