首页 > 其他分享 >27. Laravel 广播 – 私有频道

27. Laravel 广播 – 私有频道

时间:2023-02-28 13:57:16浏览次数:54  
标签:Laravel 27 console name 私有 echo user roomId log

Laravel 内置聊天室

配套视频地址:https://www.bilibili.com/video/av80196918

配置

  1. 打开 config/app.php 中 BroadcastServiceProvider 注释,即注册广播授权路由。
  2. 在 .env 中配置驱动 BROADCAST_DRIVER=redis
  3. 在 .env 中配置数据库
  4. 取消 config/database.php 中的 redis 前缀
'redis' => [
    'options' => [
        'prefix' => '',
    ],
];

安装服务

打开命令行,cd 到项目根目录下

npm install --save socket.io-client |  echo 'websocket 客户端'
npm install --save laravel-echo     |  echo 'websocket 客户端封装'
npm install -g laravel-echo-server  |  echo 'websocket 服务端'
npm install                         |  echo '安装所有其他依赖'
npm run watch                        |  echo '监控文件变化编译前端资源'
laravel-echo-server init             |  echo '初始化 websocket 服务端'
laravel-echo-server start            |  echo '启动 websocket 服务端'

初始化 websocket 客户端

在 resources/js/bootstrap.js 中添加以下代码

import Echo from "laravel-echo"

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

创建聊天室

Route::get('/login/user/{id}', fn($id) => auth()->loginUsingId($id));

Route::get('/room/{roomId}', function ($roomId) {
    broadcast(new \App\Events\Hello($roomId));
    return view('welcome', ['roomId' => $roomId]);
});

安装聊天室客户端

window.Echo.join(`chat.${roomId}`)
    .here((users) => {
        console.log(users);
    })
    .joining((user) => {
        console.log(user.name + ' 来了');
    })
    .leaving((user) => {
        console.log(user.name + ' 走了');
    });

安装频道认证路由

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
//    if ($user->canJoinRoom($roomId)) {
        return ['id' => $user->id, 'name' => $user->name];
//    }
});

定义聊天室事件

<?php

namespace App\Events;

use App\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class Hello implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;
    public $roomId;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($roomId)
    {
        $this->user = auth()->user();
        $this->roomId = $roomId;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('room.'.$this->roomId);
    }
}

开启聊天模式

监听聊天事件

window.Echo.join(`chat.${roomId}`)
    .here((users) => {
        console.log(users);
    })
    .joining((user) => {
        console.log(user.name + ' 来了');
    })
    .leaving((user) => {
        console.log(user.name + ' 走了');
    })
    .listen('NewMessage', (e) => {
        console.log(e.user.name + ":" + e.msg);
    });

定义聊天室群聊事件

<?php

namespace App\Events;

use App\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;
    public $roomId;
    public $msg;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($roomId, $msg)
    {
        $this->user = auth()->user();
        $this->roomId = $roomId;
        $this->msg = $msg;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('chat.'.$this->roomId);
    }
}

安装聊天室群聊客户端

<!doctype html>
<html lang="en">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script>
        var roomId = "{{ $roomId }}";
    </script>
    <script src="/js/app.js"></script>
</head>
<body>
    <input type="text" id="msg">
    <button onclick="axios.get('/room/{{ $roomId }}/'+document.getElementById('msg').value)">发送</button>
</body>
</html>

定义聊天室群聊路由

Route::get('/room/{roomId}/{msg}', function ($roomId, $msg) {
    broadcast(new \App\Events\NewMessage($roomId, $msg))->toOthers();
});

标签:Laravel,27,console,name,私有,echo,user,roomId,log
From: https://www.cnblogs.com/fuqian/p/17163954.html

相关文章

  • 30. Laravel 开发第三方包
    Laravel开发第三方包使用Contracts代替Facades,因为扩展包不能访问Laravel提供的所有测试Facades的辅助函数。自动发现和注册Facades"extra":{"laravel......
  • 29. Laravel 广播系统补充
    Laravel广播系统补充配套视频地址:https://www.bilibili.com/video/av80196918?p=2设置广播名称//默认是事件的类名publicfunctionbroadcastAs(){return's......
  • Laravel 最佳实践
    Laravel最佳实践翻译来源:https://github.com/alexeymezenin/laravel-best-practices单一职责原则不要这样做:publicfunctiongetFullNameAttribute(){if(aut......
  • Laravel 核心概念
    Laravel核心概念配套视频地址:https://www.bilibili.com/video/av76060293核心概念简介、服务容器、服务提供者、facade、contract、生命周期。简介我叫Laravel。......
  • 18. Laravel 模型关系:远程一对一
    Laravel模型关系:远程一对一配套视频地址:https://www.bilibili.com/video/av73028135?p=5一个帖子属于一个作者,该作者就读一所学校。帖子可通过作者访问作者所在的学校......
  • 17. Laravel 模型关系:多对多
    Laravel模型关系:多对多配套视频地址:https://www.bilibili.com/video/av73028135?p=4多对多:一个人可以扮演多个角色,一个角色可以被多个人扮演。数据结构#users:id,......
  • 19. Laravel 模型关系:远程一对多
    Laravel模型关系:远程一对多配套视频地址:https://www.bilibili.com/video/av73028135?p=5简单的说:Thread模型可以通过Author模型访问多个的Book模型。表threads......
  • 8. Laravel 视图
    Laravel视图配套视频地址https://www.bilibili.com/video/av70545323?p=8知识点返回视图给视图传递数据模版语法1.返回视图//resources/views/test.blade.p......
  • 7. Laravel 中间件
    Laravel中间件配套视频教程:https://www.bilibili.com/video/av83019817作用过滤http请求。生成中间件的命令phpartisanmake:middlewareShowAge前置与后置中......
  • 9. Laravel 内置 web 认证
    Laravel内置web认证配套视频地址:https://www.bilibili.com/video/av74879198/原理注册:用户注册成功后。在服务器端生成session文件。给用户传递session(文件名......