日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Laravel 使用 laravel-echo 和 pusher-js 实现 WebSocket 广播

發布時間:2023/12/20 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Laravel 使用 laravel-echo 和 pusher-js 实现 WebSocket 广播 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

后端配置使用

1、安裝擴展包:

composer require beyondcode/laravel-websockets

2、發布擴展包配置文件及遷移文件

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"

3、運行數據庫遷移文件

php artisan migrate

4、發布 laravel-websockets 配置文件、

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

5、安裝 pusher 的 php 擴展包 (laravel-websockets 的 api 完全兼容 pusher, 這里需要安裝)

composer require pusher/pusher-php-server "~3.0"

6、修改.env 文件中廣播程序的驅動為 pusher

BROADCAST_DRIVER=pusher

7、設置 config/broadcasting.php 中 pusher 配置

默認情況下,Laravel 應用程序廣播到 WebSocket 服務器時,是將事件信息發送到官方 Pusher 服務器。但是由于
Laravel WebSockets 包附帶了自己的 Pusher API 實現,因此我們需要告訴 Laravel
將事件發送到我們自己的服務器。

'pusher' => ['driver' => 'pusher','key' => env('PUSHER_APP_KEY'),'secret' => env('PUSHER_APP_SECRET'),'app_id' => env('PUSHER_APP_ID'),'options' => ['cluster' => env('PUSHER_APP_CLUSTER'),'encrypted' => true,'host' => '127.0.0.1','port' => 33001,'scheme' => 'http'], ],

8、配置 websockets 應用 config/websockets.php

一般情況下默認即可

9、開啟 websocket 服務

php artisan websockets:serve --port=33001

10、開啟隊列監聽

php artisan queue:listen --tries=5

11、將上邊兩個使用supervisor進程守護

12、設置nginx反向代理以啟用wss

server {listen 80;listen 443 ssl http2;#SSL-START SSL相關配置,請勿刪除或修改下一行帶注釋的404規則ssl_certificate fullchain.pem;ssl_certificate_key privkey.pem;ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;ssl_prefer_server_ciphers on;ssl_session_cache shared:SSL:10m;ssl_session_timeout 10m;add_header Strict-Transport-Security "max-age=31536000";error_page 497 https://$host$request_uri;#SSL-END# https 下的 wss 反向代理location /wss/{proxy_pass http://127.0.0.1:33001/;#當前服務器的IPproxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_set_header X-Real-IP $remote_addr;}***** }

13、生成Event

php artisan make:event OrderNotifyEvent

14、修改剛剛生成的Event文件,在app/Events目錄下

<?phpnamespace App\Events;use App\Models\Order; use Illuminate\Broadcasting\Channel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast;class OrderNotifyEvent implements ShouldBroadcast {/*** @var Order*/private $order;/*** Create a new event instance.** @param int $order_id*/public function __construct(int $order_id){$order = Order::with('hospital', 'take_delivery', 'goods_order_details.goods')->find($order_id);$this->order = $order;}/*** Get the channels the event should broadcast on.** @return \Illuminate\Broadcasting\Channel|array*/public function broadcastOn(){return new Channel('order-notify');}/*** 觸發事件時返回的數據** @return null|array*/public function broadcastWith(): ?array{return !is_null($this->order) ? $this->order->toArray() : [];} }

15、在需要推送廣播的地方調用

broadcast(new \App\Events\OrderNotifyEvent(850));

至此,后端完成


前端配置使用

1、安裝 laravel-echo 和 pusher-js 依賴

npm install laravel-echo npm install pusher-js

2、新建 laravel-echo.js 文件

import Echo from 'laravel-echo'; import Pusher from 'pusher-js';/*** pusher配置*/ const pusherConfig = {id: 'mall_pusher',key: '1e47c980dd2c0eb78b79d03dce5c8dc5',secret: '008f442bd9cd15b20a07f31d4d3b2ae7',wsHost: window.location.hostname,wsPort: 33001,wsPath: null,wssPort: 443,cluster: 'mt1',forceTLS: location.protocol === 'https:',broadcaster: 'pusher',disableStats: true,enabledTransports: ['ws', 'wss'], }if (pusherConfig.forceTLS) {pusherConfig.wsPath = '/wss'; }class LaravelEcho {static instance = null;constructor() {this.instance = new Echo({client: new Pusher(pusherConfig.key, pusherConfig),broadcaster: pusherConfig.broadcaster})}setToken(token) {this.instance.options.client.config.auth.headers.Authorization = `Bearer ${token}`}removeToken() {this.instance.options.client.config.auth.headers = {}} }export default new LaravelEcho();

3、在需要使用的地方引入

import LaravelEcho from '../utils/laravel-echo';LaravelEcho.instance.channel('order-notify').listen('OrderNotifyEvent', (e) => {if (!e || !e.id) {return;}const h = this.$createElement;const notify = this.$notify({title: '有新訂單',message: h('div', [h('span', `訂單編號:${e.order_no}`),h('a', {attrs: {href: 'javascript:void(0);',},style: {color: '#F54B64',},}, '點擊查看'),]),duration: 0,onClick: () => {this.order = Object.assign({}, this.order, e);this.modal.order_notify.show = true;notify.close();},});});

總結

以上是生活随笔為你收集整理的Laravel 使用 laravel-echo 和 pusher-js 实现 WebSocket 广播的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。