Search code examples
phpwebsocketphpwebsocket

Send data to all clients periodically


I am using Workerman along with PHPSocketIO and trying to figure out how I can send data periodically to the specified server. For some reason I can do it perfectly fine in Javascript, but I need to make notifications from PHP to all connected clients. I have attempted to use stand-alone function to connect to server and notify it via standard 'message', but for some reason it's not doing anything.

<?php

require_once __DIR__ . '/vendors/autoload.php';
use Workerman\Worker;
use PHPSocketIO\SocketIO;

static $_TERMINATE_TIME = 61;
static $_CHECK_DATA = 3;

$io = new SocketIO(1234);
$io->on('connection', function($socket){
    $socket->addedUser = false;
    echo 'New user connected' . PHP_EOL;
    $socket->broadcast->emit('message', array(
        'data'=> array('test' => 1, 'blah' => 2)
    ));
    $socket->on('message', function ($data)use($socket){
        $socket->broadcast->emit('message', array(
            'data' => array('test' => 1, 'blah' => 2)
        ));
    });
});

function HasData()
{
    echo 'Need to send server-side data to all clients ...' . PHP_EOL;
}

// Need to send notifications from the server every N seconds
\Workerman\Lib\Timer::add($_CHECK_DATA, 'HasData', null, true);
// Self-destruct server after K seconds
\Workerman\Lib\Timer::add($_TERMINATE_TIME, function() {Worker::stopAll();}, null, false);

Worker::runAll();

Solution

  • As there's no ready solution in PHP that lets me connect and request websockets server to notify all clients, we've decided to settle with classic JavaScript ping-pong and data retrieval.