Awesome Open Source
Awesome Open Source

Websocket Server

This library provides a RequestHandler to easily handle Websocket connections using amphp/http-server.


This package can be installed as a Composer dependency.

composer require amphp/websocket-server


The documentation for this library is currently a work in progress. Pull requests to improve the documentation are always welcome!


  • PHP 7.2+



// Note that this example requires:
// amphp/http-server-router
// amphp/http-server-static-content
// amphp/log

use Amp\Http\Server\HttpServer;
use Amp\Http\Server\Request;
use Amp\Http\Server\Response;
use Amp\Http\Server\Router;
use Amp\Http\Server\StaticContent\DocumentRoot;
use Amp\Log\ConsoleFormatter;
use Amp\Log\StreamHandler;
use Amp\Loop;
use Amp\Promise;
use Amp\Socket\Server;
use Amp\Success;
use Amp\Websocket\Client;
use Amp\Websocket\Message;
use Amp\Websocket\Server\ClientHandler;
use Amp\Websocket\Server\Gateway;
use Amp\Websocket\Server\Websocket;
use Monolog\Logger;
use function Amp\ByteStream\getStdout;
use function Amp\call;

require __DIR__ . '/vendor/autoload.php';

$websocket = new Websocket(new class implements ClientHandler {
    private const ALLOWED_ORIGINS = [
    public function handleHandshake(Gateway $gateway, Request $request, Response $response): Promise
        if (!\in_array($request->getHeader('origin'), self::ALLOWED_ORIGINS, true)) {
            return $gateway->getErrorHandler()->handleError(403);

        return new Success($response);

    public function handleClient(Gateway $gateway, Client $client, Request $request, Response $response): Promise
        return call(function () use ($gateway, $client): \Generator {
            while ($message = yield $client->receive()) {
                \assert($message instanceof Message);
                    '%d: %s',
                    yield $message->buffer()

Loop::run(function () use ($websocket): Promise {
    $sockets = [

    $router = new Router;
    $router->addRoute('GET', '/broadcast', $websocket);
    $router->setFallback(new DocumentRoot(__DIR__ . '/public'));

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

    $server = new HttpServer($sockets, $router, $logger);

    return $server->start();
Alternatives To Websocket Server
Select To Compare

Alternative Project Comparisons
Related Awesome Lists
Top Programming Languages
Top Projects

Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
Php (289,836
Server (65,983
Http (30,199
Websocket (13,998
Http Server (3,937
Amp (1,502
Websocket Server (893
Amphp (115
Rfc 6455 (23