php线上预览日志--3.websocket服务部署
chrome前端扩展已经准备完毕,现在开始准备websocket服务端。
这里我采用的是tp5.1+swoole+redis的方案。整体逻辑是,如果拥有注册的client_id,才能接收信息,其他人不展示。这样可以指定特定的一部分人看到日志。
下面是具体的代码实现:
<?php namespace app\swoole; use think\cache\driver\Redis; use think\swoole\Server; class WebSocket extends Server { protected $host = '0.0.0.0'; protected $port = 9502; protected $serverType = 'socket'; protected $option = [ 'worker_num'=> 4, 'daemonize' => false, 'backlog' => 128 ]; public function onMessage($server, $frame) { $redis = new \Redis(); $redis->connect('127.0.0.1', 6379); $arr = json_decode($frame->data,true); if(isset($arr['type']) && $arr['type']== 'connect'){ //判断是否具有权限 if(in_array($arr['client'],config("account."))){ $redis->hset("client_list",$arr['client'],$frame->fd); } }else if(isset($arr['type']) && $arr['type']== 'close'){ $redis->hdel("client_list",$arr['client']); }else{ } $list = $redis->hGetAll("client_list"); foreach($list as $k=>$v) { $server->push($v, $frame->data); } } public function onOpen($server,$requst){ } public function onClose($server,$fd){ $redis = new \Redis(); $redis->connect('127.0.0.1', 6379); $redis->hdel("client_list"); } public function onWorkerStart($server,$workerId){ if($workerId==0){ $redis = new \Redis(); $redis->connect('127.0.0.1', 6379); $list = $redis->hGetAll("client_list"); foreach($list as $k=>$v){ $redis->hdel("client_list",$k); } } } }