Swoole\WebSocket\Frame

Description

WebSocket data frame.

Structure

<?php
object(Swoole\WebSocket\Frame)#1 (4) {
  ["fd"]=>
  int(0)
  ["data"]=>
  NULL
  ["opcode"]=>
  int(1)
  ["finish"]=>
  bool(true)
}

  • Swoole\WebSocket\Frame->fd : The id of the WebSocket connection
  • Swoole\WebSocket\Frame->data : The data from the client.
  • Swoole\WebSocket\Frame->opcode : the opcode type of WebSocket data frame.
  • Swoole\WebSocket\Frame->finish : if the data frame is complete.

    WebSocket Frame OpCode

  • WEBSOCKET_OPCODE_TEXT = 1 : string
  • WEBSOCKET_OPCODE_BINARY = 2 : binary
  • WEBSOCKET_OPCODE_PING = 3 : ping

    Swoole\WebSocket\CloseFrame

    CloseFrame is used to disconnect a websocket connection with code and reason field.

    <?php
    object(Swoole\WebSocket\CloseFrame)#1 (6) {
      ["fd"]=>
      int(0)
      ["data"]=>
      NULL
      ["finish"]=>
      bool(true)
      ["opcode"]=>
      int(8)
      ["code"]=>
      int(1000)
      ["reason"]=>
      string(0) ""
    }
    

    WebSocket Frame Compression

    You can enable WebSocket Frame Compression by set ['websocket_compression' => TRUE] at the Websocket server.

    <?php
    // server
    use Swoole\WebSocket\Frame;
    use Swoole\WebSocket\Server;
    
    $server = new Server('127.0.0.1', 9501);
    $server->set(['websocket_compression' => true]);
    $server->on('message', function (Server $server, Frame $frame) {
        $server->push(
            $frame->fd,
            'Hello Swoole',
            SWOOLE_WEBSOCKET_OPCODE_TEXT,
            SWOOLE_WEBSOCKET_FLAG_FIN | SWOOLE_WEBSOCKET_FLAG_COMPRESS
        );
    });
    $server->start();
    
    // client
    use \Swoole\Coroutine\Http\Client;
    
    $cli = Client('127.0.0.1', 9501);
    $cli->set(['websocket_compression' => true]);
    $cli->upgrade('/');
    $cli->push(
        'Hello Swoole',
        SWOOLE_WEBSOCKET_OPCODE_TEXT,
        SWOOLE_WEBSOCKET_FLAG_FIN | SWOOLE_WEBSOCKET_FLAG_COMPRESS
    );
    

    Example

    <?php
    
    use Swoole\WebSocket\Server;
    use Swoole\Http\Request;
    use Swoole\WebSocket\Frame;
    
    $server = new Server("0.0.0.0", 9502);
    
    $server->on("start", function (Server $server) {
        echo "Swoole WebSocket Server is started at http://127.0.0.1:9502\n";
    });
    
    $server->on('open', function(Server $server, Swoole\Http\Request $request) {
        echo "connection open: {$request->fd}\n";
        $server->tick(1000, function() use ($server, $request) {
            $server->push($request->fd, json_encode(["hello", time()]));
        });
    });
    
    $server->on('message', function(Server $server, Frame $frame) {
        echo "received message: {$frame->data}\n";
        $server->push($frame->fd, json_encode(["hello", time()]));
    });
    
    $server->on('close', function(Server $server, int $fd) {
        echo "connection close: {$fd}\n";
    });
    
    $server->start();