on
(Requires Workerman version >= 3.3.0)
void \Channel\Client::on(string $event_name, callback $callback_function)
Subscribe to the $event_name event and register the callback $callback_function that will be triggered when the event occurs.
Callback Function Parameters
$event_name
The name of the event to subscribe to, which can be any string.
$callback_function
The callback function that is triggered when the event occurs. The function prototype is callback_function(mixed $event_data). $event_data is the event data passed during the event publishing.
Note:
If two callback functions are registered for the same event, the second callback function will override the first one.
Example
Multi-process Worker (multi-server), a client sends a message, broadcasting to all clients.
start.php
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
// Initialize a Channel server
$channel_server = new Channel\Server('0.0.0.0', 2206);
// websocket server
$worker = new Worker('websocket://0.0.0.0:4236');
$worker->name = 'websocket';
$worker->count = 6;
// When each worker process starts
$worker->onWorkerStart = function($worker)
{
// Channel client connects to the Channel server
Channel\Client::connect('127.0.0.1', 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 clients of the current worker process
foreach($worker->connections as $connection)
{
$connection->send($event_data);
}
});
};
$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);
};
Worker::runAll();
Test
Open Chrome browser, press F12 to open the debugging console, and enter in the Console section (or place the following code in an HTML page to run with JS)
Receiving messages connection
// Replace 127.0.0.1 with the actual IP where Workerman is running
ws = new WebSocket("ws://127.0.0.1:4236");
ws.onmessage = function(e) {
alert("Received message from server: " + e.data);
};
Broadcasting messages
ws.send('hello world');