How to Broadcast (Send to Multiple Clients) Data

Example (Scheduled Broadcasting)

use Workerman\Worker;
use Workerman\Timer;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:2020');
// The number of processes in this example must be 1
$worker->count = 1;
// Set a timer to send data to all client connections when the process starts
$worker->onWorkerStart = function($worker)
{
    // Timer, every 10 seconds
    Timer::add(10, function()use($worker)
    {
        // Iterate through all client connections of the current process and send the current server time
        foreach($worker->connections as $connection)
        {
            $connection->send(time());
        }
    });
};
// Run the worker
Worker::runAll();

Example (Group Chat)

use Workerman\Worker;
use Workerman\Timer;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:2020');
// The number of processes in this example must be 1
$worker->count = 1;
// When a message is received from a client, broadcast it to other users
$worker->onMessage = function(TcpConnection $connection, $message)use($worker)
{
    foreach($worker->connections as $connection)
    {
        $connection->send($message);
    }
};
// Run the worker
Worker::runAll();

Notes:

Single Process:
The above examples can only run in single process ($worker->count=1), because in a multi-process scenario, multiple clients may connect to different processes, and clients between processes are isolated and cannot communicate directly. This means that a client connection object in process A cannot be directly manipulated to send data to process B. (To achieve this, inter-process communication is needed, such as using the Channel component, for example, Example - Cluster Sending, Example - Group Sending).

It is recommended to use GatewayWorker
The GatewayWorker framework, developed on top of Workerman, provides a more convenient push mechanism, including multicast and broadcast. It allows for multiple processes and even multi-server deployment. If you need to push data to clients, it is recommended to use the GatewayWorker framework.

GatewayWorker manual address: https://doc2.workerman.net