最近在作一個 laravel+swoole 的聊天室一個項目,想着實現一個能夠主動觸發消息推送的功能,這個能夠實現向模板消息那個,給予全部成員發送自定義消息,而不須要經過客戶端發送消息,服務端上message中監聽傳送的消息進行作相對於的業務邏輯。php
主動消息推送實現 日常咱們採用 swoole 來寫 WebSocket 服務可能最多的用到的是open,message,close這三個監聽狀態,可是萬萬沒有看下下面的onRequest回調的使用,沒錯,解決此次主動消息推送的就是須要用onRequest回調。 官方文檔:正由於swoole_websocket_server繼承自swoole_http_server,因此在 websocket 中有onRequest回調。laravel
詳細實現:程序員
# 這裏是一個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請求。web
# 調用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 回調特別適用於須要在控制器中調用的推送消息,好比模板消息之類,在控制器中調用。性能優化
到了這裏不少朋友想深刻學習swoole和laravel,swoft微服務在使用中遇到不少困難,我爲你們準備了一套精品PHP中高級進階學習教程,須要加微信:PHPopen888,還可加入大牛學習圈子,分享tp,laravel,swoole,swoft微服務、SQL性能優化,分佈式、高併發等教程,各類大牛都是1-7年PHP開發者,天天還有11年的架構師作課程講解,助你進階中高級PHP程序員,增值漲薪!bash