Laravel 结合 Swoole WebSocket 实现服务端主动推送
需求场景
目标是构建一种能够由服务端主动触发并推送消息的机制。该功能类似于模板消息发送,允许向所有在线成员广播自定义内容,而无需等待客户端先发起请求。服务端需在 message 监听器中处理传入的消息,并执行相应的业务逻辑判断与分发。
主动推送实现思路
在使用 Swoole 开发 WebSocket 服务时,开发者通常重点关注 open、message 和 close 这三个事件监听状态。然而,解决主动推送问题的关键在于使用 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 的工作原理,接下来将在 Laravel 控制器中实现对该回调的主动触发。核心方法是通过标准的 cURL 请求向 WebSocket 服务端口发送 HTTP POST 数据,从而激活服务端的消息推送流程。
# 调用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); // 主动推送消息
总结
以上内容涵盖了基于 Laravel 和 Swoole 实现 WebSocket 主动消息推送的核心技术与代码示例。希望这些内容能为相关开发工作提供有价值的参考,感谢阅读与支持。