OpenSwoole\WebSocket\Server->push(...)

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

Declaration

<?php OpenSwoole\WebSocket\Server->push(int $fd, string $data, int $opcode = 1, int $flags = OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_FIN): bool

Parameters

fd

The file descriptor of the WebSocket connection, it can be found from the frame, must be a WebSocket client not a TCP client

data

Can only be string or binary data to send back to the client (this sets the format of the data)

opcode

The opcode of the data frame: WEBSOCKET_OPCODE_TEXT or WEBSOCKET_OPCODE_BINARY, WEBSOCKET_OPCODE_PING

flags

Set the WebSocket flag for compression

Return

If success, it returns true, otherwise it returns false

Description

Push data to the connected WebSocket client. Shall not exceed the maximum length of 2M.

Since version v4.2.0 the signature of this method has changed, before this function had $finish as the last parameter and the signature looked like:

<?php
OpenSwoole\WebSocket\Server->push(int $fd, string $data, int $opcode = WEBSOCKET_OPCODE_TEXT, bool $finish = true): bool

So after v4.2.0, the $finish parameter has been replaced with int $flags = OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_FIN instead. This is so WebSocket compression can be supported. The default is OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_FIN but you can also use OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_COMPRESS.

When sending data if you pass in a OpenSwoole\WebSocket\Frame object, OpenSwoole will handle data formatting for you, so the $data and $flags parameters will be ignored and the object will be used instead.

Example

<?php

use OpenSwoole\WebSocket\Server;
use OpenSwoole\Http\Request;
use OpenSwoole\WebSocket\Frame;

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

$server->on("Start", function(Server $server)
{
    echo "OpenSwoole WebSocket Server is started at 127.0.0.1:9501\n";
});

$server->on('Open', function(Server $server, OpenSwoole\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();
Last updated on September 20, 2022