龙空技术网

通过简易聊天室-搞定 Laravel 11 实时通信-多人聊天

无忧的松鼠u1 68

前言:

现时各位老铁们对“php在线聊天室”大概比较关怀,同学们都想要了解一些“php在线聊天室”的相关资讯。那么小编在网络上搜集了一些对于“php在线聊天室””的相关内容,希望同学们能喜欢,同学们快快来学习一下吧!

大家好呀,我是yangyang,继续给大家带来laravel11尝鲜系列文章.上一篇《通过简易聊天室-搞定 Laravel 11 实时通信-1对1聊天》我们演示整个laravel11 广播系统实时通信的全流程,而且也通过一个1对1聊天的场景进行了案例说明.接下来就简单讲一下多人聊天

定义广播路由

Broadcast::channel('user.chat.room.{id}', function ($user, $id) {    return true; // 为了方便测试,先返回 true});
修改前端页面

模拟一个房间私有频道:user.chat.room.1,然后交互代码和之前一样.

<script setup>import {Head, Link, usePage} from '@inertiajs/vue3';import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';import {ref, reactive} from 'vue';import axios from "axios";const user = usePage().props.auth.user;const canSend = ref(true)const messages = ref([    // {id: 1, receiverId: 1, uid: 2, author: 'He', content: 'Hello!'},    // {id: 2, receiverId: 1, uid: 2, author: 'He', content: 'Hi Alice!'},    // {id: 2, receiverId: 2, uid: 1, author: 'You', content: 'ddd!'},])const newMessage = ref('')defineProps({    canLogin: {        type: Boolean,    },    canRegister: {        type: Boolean,    },    laravelVersion: {        type: String,        required: true,    },    phpVersion: {        type: String,        required: true,    },});const sendMessage = () => {    if (newMessage.value.trim()) {        const messageData = {            id: new Date().getTime(),            receiverId: testReceiverId,            author: user.name,            uid: user.id,            content: newMessage.value.trim()        }        window.Echo.private('user.chat.room.1').whisper('chat.message', {            message: messageData,        }).error(result => {            console.log('error2:', result)            if (result.type === 'AuthError' && result.status === 403) {                messages.value = messages.value.filter(m => m.id !== messageData.id)                // 认证失败不显示发送                messages.value.push({                    id: new Date().getTime(),                    receiverId: 0,                    author: '系统',                    uid: 0,                    content: '授权认证失败,' + result.error                })                canSend.value = false            }        });        messages.value.push(messageData)        newMessage.value = ''        // axios.post('/push', messageData).then(response => {        //     console.log('re:', response)        // })    }};console.log('my channel:', channel)window.Echo.private('user.chat.room.1').listenForWhisper('chat.message', (data) => {    console.log('Received message:', data.message);    messages.value.push({        id: new Date().getTime(),        author: data.message.author,        content: data.message.content,    });}).error(result => {    console.log('error1:', result)    if (result.type === 'AuthError' && result.status === 403) {        // 认证失败不显示发送        messages.value.push({            id: new Date().getTime(),            receiverId: 0,            author: '系统',            uid: 0,            content: '授权认证失败,' + result.error        })        canSend.value = false    }});</script><template>    <Head title="Dashboard"/>    <AuthenticatedLayout>        <div class="bg-gray-50 text-black/50 dark:bg-black dark:text-white/50">            <div class="chat-box">                <div class="chat-messages">                    <!-- 消息列表 -->                    <div v-for="message in messages" :key="message.id" class="flex justify-between">                        <div v-if="message.uid === user.id" class="flex flex-col items-end mr-4 w-3/4">                            <span class="message-author">{{ message.author }}</span>                            <p class="message-content bg-blue-500 text-white rounded-lg p-2">{{ message.content }}</p>                        </div>                        <div v-else class="flex flex-col items-start ml-4 w-3/4">                            <span class="message-author">{{ message.author }}</span>                            <p class="message-content bg-gray-300 rounded-lg p-2">{{ message.content }}</p>                        </div>                    </div>                </div>                <!-- 输入框 -->                <div class="chat-input mt-4">                    <input v-model="newMessage" @keydown.enter="sendMessage" placeholder="输入聊天内容..."                           class="input-message w-full p-2 border rounded-lg">                    <button @click="sendMessage" v-if="canSend" class="send-button bg-blue-500 text-white px-4 py-2 rounded-lg">发送                    </button>                </div>            </div>        </div>    </AuthenticatedLayout>    <footer class="text-center padding-20 px-2 py-2 text-center text-xs text-token-text-secondary md:px-[60px]">        Laravel{{ laravelVersion }}-PHP{{ phpVersion }}    </footer></template><style scoped>/* 使用 Tailwind CSS 样式 */.chat-box {    width: 800px;    border: 1px solid #ccc;    overflow: hidden;    margin: 0 auto;}.chat-messages {    max-height: 400px;    min-height: 300px;    overflow-y: auto;}.message {    margin-bottom: 10px;}.message-author {    font-weight: bold;    margin-bottom: 5px;}.message-content {    max-width: 100%; /* 修改为 100% */}.chat-input {    display: flex;}.input-message {    flex-grow: 1;    color: #000;}.send-button {    margin-left: 10px;}</style>
总结

到目前我们已经熟悉了laravel11 broadcasting 广播系统在实时通信场景的作用,接下来的一篇将是laravel11尝鲜系列的最后一篇,该篇给大家分享一下laravel11的监控面板,同时也可以将Reverb监控起来.后续如果还有更多laravel新特性也会继续分享,敬请期待.

标签: #php在线聊天室