laravel5.8 pusher socket.io
生活随笔
收集整理的這篇文章主要介紹了
laravel5.8 pusher socket.io
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景
用于掃碼狀態,廣播事件等簡單websocket服務,框架laravel5.8
pusher
- 基于pusher外部服務,使用簡單,可以在任何框架中使用,laravel只是將發布廣播使用了事件觸發(具體觸發可以看laravel文檔),這里展示常規使用
composer require pusher/pusher-php-server
2.1 共有頻道 注意channel和event請保持一致
2.2 私有頻道
//自己定義的認證方法 ,pusher 默認post請求。public function authorize(Request $request) {$auth_key = 'xxxx';//pusher 提供的key$secret = 'xx';//pusher 提供$app_id = 'xxx';//pusher 提供app_id$option = ['cluster'=>'xx'];//pusher 提供的cluster$pusher = new Pusher\Pusher($auth_key, $secret, $app_id,$option);echo $pusher->socket_auth($request->input('channel_name'),$request->input('socket_id'));//注意必須直接輸出,防止框架后續操作}public function sendmsg(){$auth_key = 'xxxx';//pusher 提供的key$secret = 'xx';//pusher 提供$app_id = 'xxx';//pusher 提供app_id$option = ['cluster'=>'xx'];//pusher 提供的cluster$pusher = new Pusher\Pusher($auth_key, $secret, $app_id,$option);$response = $pusher->trigger('private-chat1','send-message','data:測試data','soket_id 注意是阻止發送消息的soket_id');} <head> <meta name="csrf-token" content="{{ csrf_token() }}"> </head> <script src="https://js.pusher.com/7.0/pusher.min.js"></script> <script>var pusher = new Pusher('pusher 提供的key', {authEndpoint: 'http://mobile.app.com/api/channels/authorize',//自己定義的認證路由cluster: 'pusher 提供的cluster',encrypted: true,auth: {headers: {'X-CSRF-Token': this.csrfToken}}});channel = pusher.subscribe('private-chat1');//[private-] 相當于前綴,是必須的channel.bind('send-message', function(data) {alert(JSON.stringify(data));console.log(22);console.log(data);});</script>socket.io redis
參考博文 https://blog.csdn.net/sym134/article/details/100569257
這里記錄主要流程,注意順序不要錯了,不然3,4可能執行失敗
2. 安裝所有依賴
npm install
npm install -g laravel-echo-server
npm install --save socket.io-client
npminstall --save laravel-echo
npm run dev
$ laravel-echo-server init
laravel-echo-server start
php artisan make:event ExampleEvent
<?phpnamespace App\Events;use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast;class PushMsgEvent implements ShouldBroadcast {use Dispatchable, InteractsWithSockets, SerializesModels;public $msg;/*** Create a new event instance.** @return void*/public function __construct($msg){//$this->msg =$msg;}/*** Get the channels the event should broadcast on.** @return \Illuminate\Broadcasting\Channel|array*/public function broadcastOn(){return new Channel('user1');}public function broadcastWith(){return ['data' => $this->msg];} }配置自行處理.env[BROADCAST_DRIVER=redis,QUEUE_CONNECTION=redis]
php artisan queue:listen --tries=1
到這里廣播系統就完成了,如果需要私有頻道可以繼續閱讀
14. 私有頻道
總結
以上是生活随笔為你收集整理的laravel5.8 pusher socket.io的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于win10 小爱同学UWP版本的安装
- 下一篇: 【NLP】文本情感分析