(Requires Workerman version>=3.3.0)

void \Channel\Client::on(string $event_name, callback $callback_function)

Subscribe to the event $event_name and register a callback $callback_function to be called when the event occurs.

Parameters of the Callback Function


The name of the subscribed event, which can be any string.


The callback function triggered when the event occurs. The function prototype is callback_function(mixed $event_data). $event_data is the event data passed when the event is published.


If two callback functions are registered for the same event, the latter one will override the former one.


Multi-process Worker (multiple servers), where one client sends a message and it is broadcast to all clients.


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

// Initialize a Channel server
$channel_server = new Channel\Server('', 2206);

// Websocket server
$worker = new Worker('websocket://');
$worker->name = 'websocket';
$worker->count = 6;
// When each worker process starts
$worker->onWorkerStart = function($worker)
    // The Channel client connects to the Channel server
    Channel\Client::connect('', 2206);
    // Subscribe to the 'broadcast' event and register the event callback
    Channel\Client::on('broadcast', function($event_data) use ($worker){
        // Broadcast the message to all client connections of the current worker process
        foreach ($worker->connections as $connection)

$worker->onMessage = function(TcpConnection $connection, $data)
   // Treat the data sent by the client as event data
   $event_data = $data;
   // Publish the 'broadcast' event to all worker processes
   \Channel\Client::publish('broadcast', $event_data);



Open the Chrome browser, press F12 to open the developer console, and in the Console tab, enter the following (or place the code below in an HTML page and run it with JavaScript):

For the connection receiving the message

// Replace with the actual IP where Workerman is located
ws = new WebSocket("ws://");
ws.onmessage = function(e) {
    alert("Received message from the server: " + e.data);

For broadcasting the message

ws.send('hello world');