Swoole\WebSocket\Server->push

Declaration

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

Parameters

fd

The fd of the WebSocket connection, it can be get from the frame.

data

can be string or binary data

opcode

The opcode of the frame: WEBSOCKET_OPCODE_TEXT or WEBSOCKET_OPCODE_BINARY, WEBSOCKET_OPCODE_PING

finish

If the frame is finished

Return

success

if success, it returns TRUE, otherwise it returns FALSE.

Description

Push data to the connected WebSocket client.

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();