0
user-people-family-house-home

【Laravel】利用websocket取得在線人數

本篇介紹如何在 Laravel 框架中,利用Websocket抓取在線人數。# 新增Projectlaravel new...

Posted by 冠融 on 2023-11-12 16:59:20 Views

本篇介紹如何在 Laravel 框架中,利用Websocket抓取在線人數。

# 新增Project
laravel new {project}

修改env

# .env
BROADCAST_DRIVER=pusher PUSHER_APP_ID=online PUSHER_APP_KEY=online PUSHER_APP_SECRET=onlineonline

修改bootstarp.js

# /resources/js/bootstarp.js
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
    broadcaster: 'pusher',
    encrypted: false,
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    wsHost: window.location.hostname,
    wsPort: 6001,
    forceTLS: false,
    disableStats: true
});

安裝套件

# cmd(安裝套件)
npm install
composer install
composer require pusher/pusher-php-server ^4.1
npm install --save laravel-echo pusher-js 
composer require beyondcode/laravel-websockets php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations" php artisan migrate php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

新增一個Middleware

因為會使用到Presence頻道,但它是屬於私人頻道,需要被授權才能連上。

於是我們建立一個Guest的Middleware去做認證。

namespace App\Http\Middleware;

use Closure;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AuthenticateGuest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $fakeUser = new User();
        $fakeUser->virtual_client = true;
        $fakeUser->id = rand(100,1000);
        $fakeUser->name = Str::random('10');

        $request->merge(['user' => $fakeUser]);
        $request->setUserResolver(function () use ($fakeUser) {
            return $fakeUser;
        });
        return $next($request);
    }
}

修改Provider

channel的middleware在這邊設定成剛剛建立的authenticate-guest

# BroadcastServiceProvider
public function boot() { Broadcast::routes(['middleware' => ['authenticate-guest']]); require base_path('routes/channels.php'); }

Kernel.php也要記得新增剛剛建立的authenticate-guest

# Kernel
protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'authenticate-guest' => \App\Http\Middleware\AuthenticateGuest::class, ];

啟動websocket(預設port:6001)

# 預設port:6001
php artisan websockets:serve
//
php artisan websockets:serve --port=6001

範例畫面

範例

github範本 :

 https://github.com/cc711612/Online

範本 :

 https://online.usongrat.tw/

參考文獻:

https://beyondco.de/docs/laravel-websockets/getting-started/introduction

https://learnku.com/docs/laravel/8.x/broadcasting/9388#presence-channels

View Comments