Larave广播-Pusher驱动
1、配置 .env
PUSHER_APP_ID=11111111 PUSHER_APP_KEY=bb26hfsghsdgdfgdfg PUSHER_APP_SECRET=c080dfgfdghsdgsdf PUSHER_APP_CLUSTER=mt1
APP_ID、APP_KEY、APP_SECRET从http://pusher.com网站获取
2、服务端-发送广播内容
安装pusher服务端扩展
1 composer require pusher/pusher-php-server
创建事件
php artisan make:event MyEvent
<?php
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class MyEvent implements ShouldBroadcast{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($messsage) {
$this->message = $message;
}
public function broadcastOn() {
return ['my-channel'];
}
}
服务端发送广播
1 $pusher = new Pusher\\Pusher('APP_KEY', 'APP_SECRET', 'APP_ID', array('cluster' => 'APP_CLUSTER'));
2 $data = ['message' => 'Hello World.', 'time' => time()];
3 $response = $pusher->trigger('my-channel', 'my-event, $data);
3、客户端
类库安装及使用
1 安装:npm install pusher-js
2 import Pusher from 'pusher-js/react-native' // 扩展引入
3 let pusher = new Pusher('APP_KEY', {cluster: 'mt1'}); // 创建pusher实例
4 let channel = pusher.subscribe('my-channel'); // 渠道订阅
5 channel.bind('my-event', function(data) { // 渠道事件监听
6 console.log(data)
7 });
script引入及使用
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/4.0/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('bbf6g58hfghd65f', {
cluster: 'mt1'
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
console.log(data)
// alert(data.info)
});
</script>
</head>

浙公网安备 33010602011771号