通常,我们在php开发中经常会用到简单的推送到客户端浏览器上,那么如何能打到多端浏览器同步呢?这里我们用到了websocket,基于websocket,我们可以建立服务器端到客户端的推送实例,,比如抽奖,定时更新数据等场景.
下面是一个简单的用例,可以用来启发并试着加入用户的uid做为推送标识:
<?php
/**
* push,简单版
* websocket消息推送
* <82658400@qq.com>
* @todo::需要实现uid connection
*/
require_once __DIR__ . '/../vendor/autoload.php';
use Workerman\Worker;
use Workerman\Lib\Timer;
Worker::$logFile = APP_PATH . '/log/workerman_bizpush.log';
$worker = new Worker("websocket://0.0.0.0:8091");
$worker->count = 1;
$worker->onWorkerStart = function($worker){
$redis_cfg = 'redis';
$redis_cfg = Config::env($redis_cfg);
$redis = new RedisManager(Config::$$redis_cfg[Config::REDIS_WBCSC]);
Timer::add(1, function() use($worker, $redis){
$s = $redis->get("biz_site_timer_start_key");
$e = $redis->get("biz_site_timer_end_key");
foreach($worker->connections as $connection) {
$time=date("Y-m-d H:i:s");
$connection->send($s."|".$e."|".$time);
}
});
};
Worker::runAll();
转载请注明:SuperIT » (代码分享)Workerman开发中的简单例子