主动音讯推送完成
寻常我们采纳 swoole 来写 WebSocket 效劳大概最多的用到的是open,message,close这三个监听状况,然则万万没有看下下面的onRequest回调的运用,没错,处理此次主动音讯推送的就是需要用onRequest回调。
官方文档:正因为swoole_websocket_server继续自swoole_http_server,所以在 websocket 中有onRequest回调。
细致完成:
# 这里是一个laravel中Commands # 运转php artisan swoole start 即可运转 <?php namespace App\Console\Commands; use Illuminate\Console\Command; use swoole_websocket_server; class Swoole extends Command { public $ws; /** * The name and signature of the console command. * * @var string */ protected $signature = 'swoole {action}'; /** * The console command description. * * @var string */ protected $description = 'Active Push Message'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $arg = $this->argument('action'); switch ($arg) { case 'start': $this->info('swoole server started'); $this->start(); break; case 'stop': $this->info('swoole server stoped'); break; case 'restart': $this->info('swoole server restarted'); break; } } /** * 启动Swoole */ private function start() { $this->ws = new swoole_websocket_server("0.0.0.0", 9502); //监听WebSocket衔接翻开事宜 $this->ws->on('open', function ($ws, $request) { }); //监听WebSocket音讯事宜 $this->ws->on('message', function ($ws, $frame) { $this->info("client is SendMessage\n"); }); //监听WebSocket主动推送音讯事宜 $this->ws->on('request', function ($request, $response) { $scene = $request->post['scene']; // 获取值 $this->info("client is PushMessage\n".$scene); }); //监听WebSocket衔接封闭事宜 $this->ws->on('close', function ($ws, $fd) { $this->info("client is close\n"); }); $this->ws->start(); } }
前面说的是 swoole 中onRequest的完成,下面完成下在控制器中主动触发onRequest回调。完成要领就是我们熟习的curl要求。
# 挪用activepush要领今后,会在cmd中打印出 # client is PushMessage 主动推送音讯 字眼 /** * CURL要求 * @param $data */ public function curl($data) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://127.0.0.1:9502"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HEADER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_exec($curl); curl_close($curl); } /** * 主动触发 */ public function activepush() { $param['scene'] = '主动推送音讯'; $this->curl($param); // 主动推送音讯
用处
onRequest 回调迥殊适用于需要在控制器中挪用的推送音讯,比方模板音讯之类,在控制器中挪用。
更多PHP相干学问,请接见ki4网!
以上就是用laravel+Swoole完成websocket主动音讯推送的细致内容,更多请关注ki4网别的相干文章!