简体   繁体   中英

Ratchet - How to prevent other websites from connect to my websocket server?

There's page in http://socketo.me/docs/origin talking about it, but it's completly unclear how to implement it.

This is my current code (from the tutorial at http://socketo.me/docs/push ):

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

$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', array($pusher, 'onBlogEntry'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server('0.0.0.0:8080', $loop); // 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();

Following the tutorial at http://socketo.me/docs/origin it says that i should add the variable $checkedApp to the constructor of the class HttpServer . I checked the souce code of this class, and it uses only one param in the __constructor() , and as you can see i already passed a value to this constructor, which is a instance of the class WsServer . Also the class MyHttpApp does not exist.

Aftet i searched a bit in the souce code i found the file App.php located at https://github.com/ratchetphp/Ratchet/blob/master/src/Ratchet/App.php and to implement the OriginChecker i just need to change the value of the variable $webServer to the value bellow:

$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\Http\OriginCheck(
            new Ratchet\WebSocket\WsServer(
                new Ratchet\Wamp\WampServer(
                    $pusher
                )
            ),
            array('mydomain.com') //this is the only domain that can connect to the websocket
        )
    ),
    $webSock
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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