Swoole\WebSocket\CloseFrame

Description

WebSocket data frame object. A Swoole WebSocket server since v4.2.0 will use the Swoole\WebSocket\CloseFrame object to represent WebSocket data and other attributes about the request and its data.

This object is used so that it is easy to access WebSocket data from a closed frame but also an easy way to know where the data came from, using the provided $fd property and other information about the frame. Both the server and the client Swoole services use this object.

Note: Since v4.4.12 the WebSocket service no longer uses the $finish parameter, instead it has been converted to int $flags so that multiple states can be represented as integers and constants. See the WebSocket pack() method for more information on the finish and compression flags.

Object Structure

The CloseFrame object is used to represent a disconnected websocket connection showing its status code and reason for being disconnected. For more information on disconnection codes and reasons see the Mozilla documentation on WebSocket protocol status codes.

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

The value of fd is ignored when sending the frame from server, because the value will be overwritten by the server. The fd class property is read-only.

Enable Close Frame

By default the close frame object is not enabled, to enable this you need to set the WebSocket configuration option open_websocket_close_frame.

Example

<?php

$server = new Swoole\WebSocket\Server("127.0.0.1", 9501);

$server->set(["open_websocket_close_frame" => true]));

$server->on('Open', function(Swoole\WebSocket\Server $server, $request)
{
  // ...
});

$server->on('Message', function(Swoole\WebSocket\Server $server, $frame)
{
    // WEBSOCKET_OPCODE_CLOSE (aka 0x08)
    if($frame->opcode == 0x08)
    {
        echo "Close frame received: Code {$frame->code} Reason {$frame->reason}\n";
    }
    else
    {
        echo "Message received: {$frame->data}\n";
    }
});

$server->on('Close', function ($ser, $fd)
{
  // ...
});

$server->start();