php中怎么实时推送系统消息给客户端
php中怎么实时推送系统消息给客户端,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
准备工作:安装PHP-swoole拓展;
直接贴代码;
<?phpnew class{private $_serv = null;public function __construct(){$this->_serv = new swoole_websocket_server('0.0.0.0', 6552);$this->_serv->set(array('worker_num' => 2,'dispatch_mode' => 3,'log_file' => 'swoole.log',)); //增加个监听端口 $udpworker = $this->_serv->listen("127.0.0.1", 6553, SWOOLE_SOCK_UDP);$udpworker->on('Packet', function ($serv, $data, $addr) {$data = json_decode($data, true);if(!empty($data)){//你的业务逻辑 }});$this->_serv->on('open', array($this, 'onStart'));$this->_serv->on('message', array($this, 'onMessage'));$this->_serv->on('close', array($this, 'onClose'));$this->_serv->start();}public function onStart($serv, $request){echo "server: connect success with fd {$request->fd}\n";}//format:'{"school_class_id":"1","school_id":"2"}' public function onMessage($serv, $frame){ /**start*你的业务逻辑***/}public function onClose($serv, $fd){echo "client {$fd} closed\n";}}?>
原理:首先创建websocket服务器对象,监听0.0.0.0:6552端口,然后在用服务对象去监听UDP 6553的端口。客户端消息发送到6553借口,然后在通过6552端口发送给用户。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。