php socket laravel,Laravel利用swoole 实现websocket 主动消息推送

需求

需要实现一个可以主动触发消息推送的功能,这个可以实现向模板消息那个,给予所有成员发送自定义消息,而不需要通过客户端发送消息,服务端上message中监听传送的消息进行做相对于的业务逻辑。

主动消息推送实现

平常我们采用 swoole 来写 WebSocket 服务可能最多的用到的是open,message,close这三个监听状态,但是万万没有看下下面的onRequest回调的使用,没错,解决这次主动消息推送的就是需要用onRequest回调。

官方文档:正因为swoole_websocket_server继承自swoole_http_server,所以在 websocket 中有onRequest回调。

详细实现:

# 这里是一个laravel中Commands

# 运行php artisan swoole start 即可运行

namespace AppConsoleCommands;

use IlluminateConsoleCommand;

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 SendMessagen");

});

//监听WebSocket主动推送消息事件

$this->ws->on('request', function ($request, $response) {

$scene = $request->post['scene']; // 获取值

$this->info("client is PushMessagen".$scene);

});

//监听WebSocket连接关闭事件

$this->ws->on('close', function ($ws, $fd) {

$this->info("client is closen");

});

$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); // 主动推送消息

或许很多PHPer到了这里很多朋友想进阶高级程序员、架构师!想深入学习swoole和laravel、thinkphp,swoft微服务在使用中遇到很多困难,为了大家都能够早日进阶PHP架构师,可以参考下这份PHP架构师路线图跟架构教程,请戳这里

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值