您好,登錄后才能下訂單哦!
在Laravel中可以通過(guò)使用Laravel Echo和Laravel WebSockets來(lái)實(shí)現(xiàn)實(shí)時(shí)聊天應(yīng)用。下面是實(shí)現(xiàn)步驟:
composer require beyondcode/laravel-websockets
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
php artisan migrate
config/broadcasting.php
文件中配置:'connections' => [
'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'),
'useTLS' => true,
],
],
],
.env
文件中配置 Pusher 相關(guān)信息:PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-app-key
PUSHER_APP_SECRET=your-pusher-app-secret
PUSHER_APP_CLUSTER=your-pusher-app-cluster
php artisan make:event MessageSent
在事件類的構(gòu)造函數(shù)中傳入消息內(nèi)容:
public $message;
public function __construct($message)
{
$this->message = $message;
}
php artisan make:channel ChatChannel
在頻道認(rèn)證類中,授權(quán)用戶訪問(wèn)頻道:
public function join($user, $channel)
{
return true;
}
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-app-key',
cluster: 'your-pusher-app-cluster',
encrypted: true,
});
window.Echo.channel('chat')
.listen('MessageSent', (e) => {
console.log(e.message);
});
use App\Events\MessageSent;
$message = "Hello, world!";
broadcast(new MessageSent($message))->toOthers();
這樣就可以在 Laravel 中使用 WebSockets 實(shí)現(xiàn)實(shí)時(shí)聊天應(yīng)用了。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。