用laravel+Swoole实现websocket主动消息推送
Laravel  /  管理员 发布于 5年前   346
近来有个需求:想实现一个可以主动触发消息推送的功能,这个可以实现向模板消息那个,给予所有成员发送自定义消息,而不需要通过客户端发送消息,服务端上message中监听传送的消息进行做相对于的业务逻辑。
主动消息推送实现
平常我们采用 swoole 来写 WebSocket 服务可能最多的用到的是open,message,close这三个监听状态,但是万万没有看下下面的onRequest回调的使用,没错,解决这次主动消息推送的就是需要用onRequest回调。
官方文档:正因为swoole_websocket_server继承自swoole_http_server,所以在 websocket 中有onRequest回调。
详细实现:
# 这里是一个laravel中Commands# 运行php artisan swoole start 即可运行<?phpnamespace 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相关知识,请访问!
以上就是用laravel+Swoole实现websocket主动消息推送的详细内容,更多请关注其它相关文章!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号