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;
});

发表评论