amphp / websocket-server

WebSocket component for PHP based on the Amp HTTP server.
MIT License
114 stars 17 forks source link

Example up to date ? #14

Closed elovin closed 4 years ago

elovin commented 4 years ago

I couldn't get the example in the readme to work with the current 2.0 RC version.

This is the example that did work after some adjustments:

<?php

use Amp\Http\Server\HttpServer;
use Amp\Http\Server\Request;
use Amp\Http\Server\Response;
use Amp\Log\StreamHandler;
use Amp\Loop;
use Amp\Promise;
use Amp\Success;
use Amp\Websocket\Client;
use Amp\Websocket\Server\Websocket;
use Monolog\Logger;
use function Amp\ByteStream\getStdout;

require 'vendor/autoload.php';

$websocket = new class extends Websocket {

    /**
     * @inheritDoc
     */
    protected function onHandshake(Request $request, Response $response): Promise
    {
        return new Success($response);
    }

    /**
     * @inheritDoc
     */
    protected function onConnect(Client $client, Request $request, Response $response): ?Promise
    {
        return Amp\call(function () use ($client) {
            while ($message = yield $client->receive()) {
                $payload = yield $message->buffer();
                yield $client->send('Message of length ' . \strlen($payload) . 'received');
            }
        });
    }
};

$logHandler = new StreamHandler(getStdout());
$logger = new Logger('server');
$logger->pushHandler($logHandler);

$server = new HttpServer([\Amp\Socket\Server::listen('0.0.0.0:8080')], $websocket, $logger);

Loop::run(function () use ($server) {
    yield $server->start();
});
kelunik commented 4 years ago

The example might be out of date, yes. Want to send that as a PR?

elovin commented 4 years ago

Let me test it with the current git master then I will create a pull request.

Okay my bad there is already a new example (its however a broadcast ws server example) its just not in the readme.

examples/broadcast-server/server.php

I did create a pull request for my example (works with current git master) if you think its useful you can merge it.

15