Swoole\WebSocket\Server::pack()

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\WebSocket\Server::pack(string $data, int $opcode = WEBSOCKET_OPCODE_TEXT, int $flags = SWOOLE_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 SWOOLE_WEBSOCKET_FLAG_FIN.

Return

If success, it returns a Swoole\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 SWOOLE_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 Swoole\Server('127.0.0.1', 9501 , SWOOLE_PROCESS);

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

$server->on('WorkerStart', function(Swoole\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: swoole-http-server\r\n\r\n";

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

$server->start();
Last updated on August 31, 2022