近來有個需求:想實現一個能夠主動觸發消息推送的功能,這個能夠實現向模板消息那個,給予全部成員發送自定義消息,而不須要經過客戶端發送消息,服務端上message中監聽傳送的消息進行作相對於的業務邏輯。php
主動消息推送實現
日常咱們採用 swoole 來寫 WebSocket 服務可能最多的用到的是open,message,close這三個監聽狀態,可是萬萬沒有看下下面的onRequest回調的使用,沒錯,解決此次主動消息推送的就是須要用onRequest回調。
官方文檔:正由於swoole_websocket_server繼承自swoole_http_server,因此在 websocket 中有onRequest回調。html
詳細實現:laravel
1 # 這裏是一個laravel中Commands 2 # 運行php artisan swoole start 便可運行 3 <?php 4 5 namespace App\Console\Commands; 6 7 use Illuminate\Console\Command; 8 use swoole_websocket_server; 9 10 class Swoole extends Command 11 { 12 public $ws; 13 /** 14 * The name and signature of the console command. 15 * 16 * @var string 17 */ 18 protected $signature = 'swoole {action}'; 19 20 /** 21 * The console command description. 22 * 23 * @var string 24 */ 25 protected $description = 'Active Push Message'; 26 27 /** 28 * Create a new command instance. 29 * 30 * @return void 31 */ 32 public function __construct() 33 { 34 parent::__construct(); 35 } 36 37 /** 38 * Execute the console command. 39 * 40 * @return mixed 41 */ 42 public function handle() 43 { 44 $arg = $this->argument('action'); 45 switch ($arg) { 46 case 'start': 47 $this->info('swoole server started'); 48 $this->start(); 49 break; 50 case 'stop': 51 $this->info('swoole server stoped'); 52 break; 53 case 'restart': 54 $this->info('swoole server restarted'); 55 break; 56 } 57 } 58 59 /** 60 * 啓動Swoole 61 */ 62 private function start() 63 { 64 $this->ws = new swoole_websocket_server("0.0.0.0", 9502); 65 //監聽WebSocket鏈接打開事件 66 $this->ws->on('open', function ($ws, $request) { 67 }); 68 //監聽WebSocket消息事件 69 $this->ws->on('message', function ($ws, $frame) { 70 $this->info("client is SendMessage\n"); 71 }); 72 //監聽WebSocket主動推送消息事件 73 $this->ws->on('request', function ($request, $response) { 74 $scene = $request->post['scene']; // 獲取值 75 $this->info("client is PushMessage\n".$scene); 76 }); 77 //監聽WebSocket鏈接關閉事件 78 $this->ws->on('close', function ($ws, $fd) { 79 $this->info("client is close\n"); 80 }); 81 $this->ws->start(); 82 } 83 }
前面說的是 swoole 中onRequest的實現,下面實現下在控制器中主動觸發onRequest回調。實現方法就是咱們熟悉的curl請求。web
1 # 調用activepush方法之後,會在cmd中打印出 2 # client is PushMessage 主動推送消息 字眼 3 /** 4 * CURL請求 5 * @param $data 6 */ 7 public function curl($data) 8 { 9 $curl = curl_init(); 10 curl_setopt($curl, CURLOPT_URL, "http://127.0.0.1:9502"); 11 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 12 curl_setopt($curl, CURLOPT_HEADER, 1); 13 curl_setopt($curl, CURLOPT_POST, 1); 14 curl_setopt($curl, CURLOPT_POSTFIELDS, $data); 15 curl_exec($curl); 16 curl_close($curl); 17 } 18 19 /** 20 * 主動觸發 21 */ 22 public function activepush() 23 { 24 $param['scene'] = '主動推送消息'; 25 $this->curl($param); // 主動推送消息
用途
onRequest 回調特別適用於須要在控制器中調用的推送消息,好比模板消息之類,在控制器中調用。thinkphp
推薦閱讀:編程
PHP 當Swoole 趕上 ThinkPHP5websocket
Swoole和Redis實現的併發隊列處理系統swoole