workerman channel組件集羣推送

<?php
use Workerman\Worker;

require_once '../../web/Workerman/Autoloader.php';
require_once '../../web/Channel/src/Server.php';
require_once '../../web/Channel/src/Client.php';

$worker = new Worker('text://0.0.0.0:0623');

$channel = new Channel\Server('0.0.0.0', 8888);

$worker->count = 3;
$worker->onWorkerStart = function ($worker)
{
\Channel\Client::connect('127.0.0.1', 8888);
\Channel\Client::on('broadcast', function($event_data)use($worker){
$event_data = json_decode($event_data);
if (!empty($event_data->work_id) && !empty($event_data->to_connect_id)) {
$worker_id = $event_data->work_id;
$to_connect_id = $event_data->to_connect_id;
if ($worker_id == $worker->id) {
foreach ($worker->connections as $connection) {
if ($connection->id == $to_connect_id) {
$connection->send($event_data->content);
}
}
}
} else {
foreach ($worker->connections as $connection) {
$connection->send($event_data['content']);
}
}
});
};
$worker->onConnect = function ($connection)use($worker)
{
echo '用戶姐夫' . 'worker id ' . $worker->id . ',connection id ' . $connection->id . "上線\n";};$worker->onMessage = function ($connection, $data)use($worker){ echo '用戶姐夫' . 'worker id ' . $worker->id . ',connection id ' . $connection->id . "上線\n"; $event_data['content'] = $data; $event_data['work_id'] = 2; $event_data['to_connect_id'] = 2;//這裏模擬只向work進程id爲2 connect id 爲2 的tcp連接發送信息 $data_event = json_encode($event_data); Channel\Client::publish('broadcast', $data_event);};Worker::runAll();
相關文章
相關標籤/搜索