Skip to content

Instantly share code, notes, and snippets.

@cspray
Last active September 22, 2019 13:48
Show Gist options
  • Save cspray/630ee9bcbea3854ec74366ec23bbc0ec to your computer and use it in GitHub Desktop.
Save cspray/630ee9bcbea3854ec74366ec23bbc0ec to your computer and use it in GitHub Desktop.
cspray/websocket-commands Quick Start
<?php
namespace MyApp\Command;
use Amp\Promise;
use Amp\Websocket\Client;
use Cspray\WebsocketCommands\ClientPayload;
use Cspray\WebsocketCommands\WebsocketCommand;
use function Amp\Promise\call;
final class EchoCommand implements WebsocketCommand {
public function getName() : string {
return 'echo';
}
public function execute(Client $client, ClientPayload $payload) : Promise {
return call(function() use ($client, $clientPayload) {
$echoBack = $clientPayload->get('data.param');
yield $client->send($echoBack);
});
}
}
<?php
namespace MyApp\Middleware;
use Amp\Websocket\Client;
use Amp\Promise;
use Cspray\WebsocketCommands\ClientPayload;
use Cspray\WebsocketCommands\WebsocketCommandMiddleware;
use Cspray\WebsocketCommands\Enum\MiddlewareChain;
use function Amp\Promise\call;
final class EchoMiddleware implements WebsocketCommandMiddleware {
public function handleClient(Client $client, ClientPayload $clientPayload) : Promise {
return call(function() use($clientPayload) {
if (!$clientPayload->has('data.param')) {
$clientPayload->set('data.param', 'Nothing to echo');
}
// returning null implies MiddlewareChain::Continue but we like to be explicit
return MiddlewareChain::Continue();
});
}
}
<?php
namespace MyApp;
use MyApp\Command\EchoCommand;
use Amp\ByteStream\ResourceOutputStream;
use Amp\Http\Server\Router;
use Amp\Http\Server\Server;
use Amp\Http\Server\StaticContent\DocumentRoot;
use Amp\Log\ConsoleFormatter;
use Amp\Log\StreamHandler;
use Amp\Loop;
use Amp\Promise;
use Amp\Websocket\Client;
use Cspray\WebsocketCommands\ClientPayload;
use Cspray\WebsocketCommands\CommandPoweredWebsocket;
use Cspray\WebsocketCommands\OriginHostMatchingHandshakeAuthenticator;
use Monolog\Logger;
$hosts = ['http://127.0.0.1:1337', 'http://localhost:1337', 'http://[::1]:1337'];
$handshakeAuthenticator = new OriginHostMatchingHandshakeAuthenticator($hosts)
$websocket = new CommandPoweredWebsocket($handshakeAuthenticator);
$websocket->addCommand(new EchoCommand(), new EchoMiddleware());
$router = new Router();
$router->addRoute('GET', '/app', $websocket);
$router->setFallback(new DocumentRoot(__DIR__ . '/public'));
$logHandler = new StreamHandler(new ResourceOutputStream(\STDOUT));
$logHandler->setFormatter(new ConsoleFormatter());
$logger = new Logger('websocket-commands');
$logger->pushHandler($logHandler);
$sockets = [listen('127.0.0.1:1337'), listen('[::1]:1337')];
$server = new Server($sockets, $router, $logger);
Loop::run(function() use ($server) {
yield $server->start();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment