企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 官方文档: https://www.workerman.net/doc/workerman/components/channel.html ## 发布订阅,类似于广播的效果所有链接的人都能看到 ~~~ <?php require_once 'workerman/Autoloader.php'; require_once 'channel-master/src/Server.php'; require_once 'channel-master/src/Client.php'; use Workerman\Worker; use Channel\Client; use Channel\Server; //服务端与客户端合并到一起用 //------------服务端------------------// $channel_server = new Server('0.0.0.0',6666); //------------客户端------------------// $worker=new Worker('text://0.0.0.0:7777'); $worker->onWorkerStart=function($worker){ Client::connect('127.0.0.1',6666); //以下为订阅消息 Client::on('broadcast', function($data)use($worker){ //订阅消息 ‘broadcast’ // 向当前worker进程的所有客户端广播消息 foreach($worker->connections as $connection) { $connection->send($data); } }); //以下为发布消息 $worker->onMessage=function ($connection,$data){ //发布消息 Client::publish('broadcast',$data); }; }; Worker::runAll(); ~~~ ## 取消订阅 ``` Client::unsubscribe('broadcast') ``` ## 注意要连接客户端的链接: IP:7777 ![](https://img.kancloud.cn/c4/e6/c4e6bce3f31832cda00d84eb98539f7a_1337x935.png)