29. Laravel 广播系统补充

Laravel 广播系统补充

配套视频地址:https://www.bilibili.com/video/av80196918?p=2

设置广播名称

// 默认是事件的类名
public function broadcastAs()
{
    return 'server.created';
}

//     .listen('.server.created', (e) => {
//         console.log(e);
//     });

增加广播数据

// 默认只包含 public 属性
public function broadcastWith()
{
    return ['id' => $this->user->id];
}

自定义授权端点

// 默认 broadcasting/auth
window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
    authEndpoint: '/custom/endpoint/auth'
});

定义频道授权

Broadcast::channel('channel', function() {
    // ...
}, ['guards' => ['web', 'admin']]);

定义频道类

php artisan make:channel OrderChannel
use App\Broadcasting\OrderChannel;

Broadcast::channel('order.{order}', OrderChannel::class);
<?php

namespace App\Broadcasting;

use App\Order;
use App\User;

class OrderChannel
{
    /**
     * Create a new channel instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Authenticate the user's access to the channel.
     *
     * @param  \App\User  $user
     * @param  \App\Order  $order
     * @return array|bool
     */
    public function join(User $user, Order $order)
    {
        return $user->id === $order->user_id;
    }
}

获取当前连接的 socketId

var socketId = Echo.socketId();

监听多个事件

Echo.private('orders')
    .listen(...)
    .listen(...)
    .listen(...);

退出频道

在 Echo 实例上调用 leaveChannel 方法,可以退出公有频道:

Echo.leaveChannel('orders');

调用 leave 方法,可以退出公有频道、私有频道和在线频道:

Echo.leave('orders');

定制命名空间

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
    namespace: 'App.Other.Namespace'    // 默认 App\Events
});

客户端事件

<!doctype html>
<html lang="en">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="/js/app.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var roomId = "{{ $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);
            });

        Echo.private('chat')
            .listenForWhisper('typing', (e) => {
                console.log('typing...');
                console.log(e);
            });
    </script>

</head>
<body>
<div id="app">
    <input type="text" id="msg" v-model="msg">

    <button onclick="axios.get('/room/{{ $roomId }}/'+document.getElementById('msg').value)">发送</button>
</div>


</body>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                msg: ''
            }
        },
        watch: {
            msg(value) {
                Echo.private('chat')
                    .whisper('typing', {
                        roomId: roomId
                    });
            }
        }
    })
</script>
</html>
Broadcast::channel('chat', function () {
    return true;
});

posted on   何苦->  阅读(47)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示