Socket.IO 是一个库,可以在客户端和服务器之间实现 低延迟, 双向 和 基于事件的 通信.
效果展示
安装依赖
// 后端插件安装
npm i socket.io -S
// 前端插件安装
npm i socket.io-client -S
前端搭建及逻辑
<script setup>
import { ref, onMounted, nextTick } from 'vue';
import io from 'socket.io-client';
const username = ref('');
const socket = io('http://192.168.1.92:3000');
const val = ref('');
const messages = ref([]);
const isUsernameConfirmed = ref(false);
const room = ref('');
const userList = ref([]);
const messageContainer = ref(null);
const confirmUsername = () => {
if (!username.value) {
alert('请输入用户名');
return;
}
isUsernameConfirmed.value = true;
};
const joinRoom = () => {
if (room.value.trim().length === 0) {
return; // 禁止加入空房间
}
if (!room.value) {
alert('请输入房间号');
return;
}
socket.emit('joinRoom', JSON.stringify({ username: username.value, room: room.value }));
};
const sendMessage = () =>