amphp/websocket-client

repository·2.x·Indexed 41 days ago

https://github.com/amphp/websocket-client

An asynchronous WebSocket client for PHP 8.1+ built on the Amp framework. It provides full-duplex, real-time communication via the connect() function and WebsocketConnector, supporting text and binary data transmission, custom heartbeats, and rate limiting.

Tokens
1.4K
Snippets
4
Records
6
Agent score
1%

What's inside amphp/websocket-client

  1. Connect to a WebSocket server

    2.x

    You can establish a WebSocket connection using the Amp\Websocket\Client\connect() function or by using a WebsocketConnector instance.

    Using connect()

    The connect() function accepts a string URI, a PSR-7 UriInterface instance, or a WebsocketHandshake object. URIs must use the ws or wss scheme.

    <?php
    
    require 'vendor/autoload.php';
    
    use function Amp\\Websocket\\Client\\connect;
    
    // Connects to a local websocket server
    $connection = connect('ws://localhost:1337/websocket');
    
    foreach ($connection as $message) {
        // $message is an instance of Amp\\Websocket\\WebsocketMessage
    }
    <?php
    
    require 'vendor/autoload.php';
    
    use function Amp\Websocket\Client\connect;
    
    // Amp\Websocket\Client\connect() uses the WebsocketConnection instance
    // defined by Amp\Websocket\Client\websocketConnector()
    $connection = connect('ws://localhost:1337/websocket');
    
    foreach ($connection as $message) {
        // $message is an instance of Amp\Websocket\WebsocketMessage
    }
  2. Receive and buffer WebSocket messages

    2.x

    Messages can be received using Connection::receive(), which returns a WebsocketMessage instance. This supports streaming large messages.

    For most use cases where messages are small, you can buffer the entire message by calling $message->buffer() or by casting the message object to a string.

    Note on message limits: The maximum message length is determined by the messageSizeLimit option in the WebsocketParserFactory (default is 10 MiB).

    use Amp\Websocket\Client\WebsocketHandshake;
    use Amp\Websocket\WebsocketCloseCode;
    use function Amp\Websocket\Client\connect;
    
    // Connects to the websocket endpoint at libwebsockets.org
    // which sends a message every 50ms.
    $handshake = (new WebsocketHandshake('wss://libwebsockets.org'))
        ->withHeader('Sec-WebSocket-Protocol', 'dumb-increment-protocol');
    
    $connection = connect($handshake);
    
    foreach ($connection as $message) {
        $payload = $message->buffer();
    
        printf("Received: %s\n", $payload);
    
        if ($payload === '100') {
            $connection->close();
            break;
        }
    }
    use Amp\Websocket\Client\WebsocketHandshake;
    use Amp\Websocket\WebsocketCloseCode;
    use function Amp\Websocket\Client\connect;
    
    // Connects to the websocket endpoint at libwebsockets.org
    // which sends a message every 50ms.
    $handshake = (new WebsocketHandshake('wss://libwebsockets.org'))
        ->withHeader('Sec-WebSocket-Protocol', 'dumb-increment-protocol');
    
    $connection = connect($handshake);
    
    foreach ($connection as $message) {
        $payload = $message->buffer();
    
        printf("Received: %s\n", $payload);
    
        if ($payload === '100') {
            $connection->close();
            break;
        }
    }
  3. Send text or binary data via WebSocket

    2.x

    Use the following methods on a Connection instance to send data:

    • Connection::sendText(string $data): Sends a text message. The data must be valid UTF-8.
    • Connection::sendBinary(string $data): Sends a binary message. The data can be arbitrary.

    Note: These methods return as soon as the message is written to the local send buffer; they do not guarantee the remote party has received it.

  4. Configure custom connection parameters with WebsocketHandshake and WebsocketConnector

    2.x

    For advanced configurations, you can provide a customized WebsocketConnectionFactory to an Rfc6455Connector. This allows you to control heartbeats, rate limits, message size limits, and more.

    use Amp\Websocket\Client\Rfc6455ConnectionFactory;
    use Amp\Websocket\Client\Rfc6455Connector;
    use Amp\Websocket\Client\WebsocketHandshake;
    use Amp\Websocket\ConstantRateLimit;
    use Amp\Websocket\Parser\Rfc6455ParserFactory;
    use Amp\Websocket\PeriodicHeartbeatQueue;
    
    $connectionFactory = new Rfc6455ConnectionFactory(
        heartbeatQueue: new PeriodicHeartbeatQueue(
            heartbeatPeriod: 5, // 5 seconds
        ),
        rateLimit: new ConstantRateLimit(
            bytesPerSecondLimit: 2 ** 17, // 128 KiB
            framesPerSecondLimit: 10,
        ),
        parserFactory: new Rfc6455ParserFactory(
            messageSizeLimit: 2 ** 20, // 1 MiB
        ),
        frameSplitThreshold: 2 ** 14, // 16 KiB
        closePeriod: 0.5, // 0.5 seconds
    );
    
    $connector = new Rfc6455Connector($connectionFactory);
    
    $handshake = new WebsocketHandshake('wss://example.com/websocket');
    $connection = $connector->connect($handshake);
    use Amp\Websocket\Client\Rfc6455ConnectionFactory;
    use Amp\Websocket\Client\Rfc6455Connector;
    use Amp\Websocket\Client\WebsocketHandshake;
    use Amp\Websocket\ConstantRateLimit;
    use Amp\Websocket\Parser\Rfc6455ParserFactory;
    use Amp\Websocket\PeriodicHeartbeatQueue;
    
    $connectionFactory = new Rfc6455ConnectionFactory(
        heartbeatQueue: new PeriodicHeartbeatQueue(
            heartbeatPeriod: 5, // 5 seconds
        ),
        rateLimit: new ConstantRateLimit(
            bytesPerSecondLimit: 2 ** 17, // 128 KiB
            framesPerSecondLimit: 10,
        ),
        parserFactory: new Rfc6455ParserFactory(
            messageSizeLimit: 2 ** 20, // 1 MiB
        ),
        frameSplitThreshold: 2 ** 14, // 16 KiB
        closePeriod: 0.5, // 0.5 seconds
    );
    
    $connector = new Rfc6455Connector($connectionFactory);
    
    $handshake = new WebsocketHandshake('wss://example.com/websocket');
    $connection = $connector->connect($handshake);