OpenSwoole\WebSocket\Server::pack()

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\WebSocket\Server::pack(string $data, int $opcode = WEBSOCKET_OPCODE_TEXT, int $flags = OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_FIN): string

Parameters

data

The message content you want to pack into a frame.

opcode

The OpCode which specifies the data format (see list below), the default is text.

flags

Set options using constants which add support for things like compression or if the frame is complete, default is OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_FIN.

Return

If success, it returns a OpenSwoole\WebSocket\Frame object

Description

Pack data into a WebSocket Frame.

A WebSocket frame is useful because all the details are stored within one object and you can enable things like compression and set the data format. A frame can then be passed around, set to completed and then sent back to the client etc.

Old API

Since v4.4.12 the flags parameter was originally bool finish and that allowed you to indicate if frame data was complete or not. But in time there are more options to set, so finish was changed to int flags. The default is OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_FIN, meaning that the frame is complete but there are other options for compression, see WebSocket Frame for more information on the new flags.

Also since v4.4.12 the ending bool mask parameter has been removed. It allowed you to specify if you wanted the mask to be set, the original default was false.

WebSocket Frame OpCodes

You can set these OpCodes

  • WEBSOCKET_OPCODE_TEXT = 1: String data
  • WEBSOCKET_OPCODE_BINARY = 2: Binary data
  • WEBSOCKET_OPCODE_PING = 3: Ping packet

Example

<?php

$server = new OpenSwoole\Server('127.0.0.1', 9501 , OpenSwoole\Server::POOL_MODE);

$server->set([
    'log_file' => '/dev/null',
]);

$server->on('WorkerStart', function(OpenSwoole\Server $server)
{
    // ...
});

$server->on('Receive', function($server, $fd, $threadId, $data)
{
    $sendData = "HTTP/1.1 101 Switching Protocols\r\n";
    $sendData .= "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: IFpdKwYy9wdo4gTldFLHFh3xQE0=\r\n";
    $sendData .= "Sec-WebSocket-Version: 13\r\nServer: OpenSwoole-http-server\r\n\r\n";

    $sendData .= OpenSwoole\WebSocket\Server::pack("Hello World!\n");
    $server->send($fd, $sendData);
});

$server->start();
Last updated on September 20, 2022