Last active
March 29, 2018 13:39
-
-
Save BrainFeeder/74fbd988ea24ac941514c187f6c1700b to your computer and use it in GitHub Desktop.
Setting up websockets with Ratchet and React in php (TLS/WSS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require dirname(__DIR__) . '/vendor/autoload.php'; | |
$loop = React\EventLoop\Factory::create(); | |
$pusher = new Pusher; // Create a Pusher class that implements Ratchet\Wamp\WampServerInterface | |
// The loop | |
// Binding to 127.0.0.1 means the only client that can connect is itself. | |
// To accept remotes we should bind to 0.0.0.0 | |
$context = new React\ZMQ\Context($loop); | |
$pull = $context->getSocket(ZMQ::SOCKET_PULL); | |
$pull->bind('tcp://0.0.0.0:5555'); | |
$pull->on('error', array($pusher, 'onError')); | |
$pull->on('message', array($pusher, 'onLogIn')); | |
// Set up our WebSocket server with TLS | |
$webSock = new React\Socket\SecureServer( | |
new React\Socket\Server($loop), | |
$loop, | |
array( | |
'local_cert' => '/var/xxxx/combined.pem', | |
//'allow_self_signed' => true, | |
'verify_peer' => false | |
) | |
); | |
// And listen | |
$webSock->listen(8080, '0.0.0.0'); | |
// Server | |
$webServer = new Ratchet\Server\IoServer( | |
new Ratchet\Http\HttpServer( | |
new Ratchet\WebSocket\WsServer( | |
new Ratchet\Wamp\WampServer( | |
$pusher | |
) | |
) | |
), | |
$webSock | |
); | |
/// $wsServer->enableKeepAlive($server->loop, 30); http://socketo.me/docs/migration-3 | |
// $webSock->enableKeepAlive($loop, 30); Dont't know about this? Could *maybe* be used to handle crashes? | |
/* periodicTimer | |
$loop->addPeriodicTimer(5, function () { | |
$memory = memory_get_usage() / 1024; | |
$formatted = number_format($memory, 3).'K'; | |
echo "Current memory usage: {$formatted}\n"; | |
}); | |
*/ | |
// Go go go! | |
$loop->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment