效果图
逻辑分析
- 创建nodejs-websocket
- 根据消息类型区分系统消息和普通消息
- 使用浏览器指纹来设置用户信息(正常情况应使用后端提供的用户信息)
- 根据消息的userId显示是谁发的消息和自己发送的消息
核心代码
const PORT = 3600
const ws = require('nodejs-websocket');
//封装发送消息的函数(向每个链接的用户发送消息)
const boardCast = (str) => {
server.connections.forEach((connect) => {
connect.sendText(str)
})
};
//封装获取所有聊天者的nickname
const getAllChatter = () => {
let chatterArr = [];
server.connections.forEach((connect) => {
let hasUser = false
chatterArr.forEach(itm => {
if (itm.userId === connect.userId) {
hasUser = true
if (itm.nickname !== connect.nickname) {
itm.nickname = connect.nickname
}
}
})
if (!hasUser) {
chatterArr.push({ nickname: connect.nickname, userId: connect.userId })
}
});
return chatterArr;
};
const server = ws.createServer((connect) => {
//链接上来的时候
connect.on('text', (str) => {
let data = JSON.parse(str);
switch (data.type) {
case 'system':
connect.nickname = data.nickname;
connect.userId = data.userId;
connect.color = data.color;
boardCast(JSON.stringify({
type: 'system',
message: data.nickname + "进入房间",
}));
boardCast(JSON.stringify({
type: 'chatterList',
list: getAllChatter()
}));
break;
case 'chat':
boardCast(JSON.stringify({
userId: connect.userId,
type: 'chat',
color: data.color,
nickname: connect.nickname,
message: data.message
}));
break;
default:
break;
}
});
//关闭链接的时候
connect.on('close', () => {
//离开房间
boardCast(JSON.stringify({
type: 'system',
message: connect.nickname + '离开房间'
}));
//从在线聊天的人数上面除去
boardCast(JSON.stringify({
type: 'chatterList',
list: getAllChatter()
}))
});
//错误处理
connect.on('error', (err) => {
console.log(err);
})
}).listen(PORT, () => {
console.log("running")
});
<template>
<div class="chat-room">
<div class="nav"></div>
<div class="main">
<div class="title">
<span>修真聊天群({{ userCount }})</span>
</div>
<div class="content" v-scrollbar ref="recordsContent">
<ul>
<li v-for="(itm, inx) in records" :key="inx">
<system-message v-if="itm.type === 'system'" :name="itm.nickname" :text="itm.message"></system-message>
<my-message v-if="itm.type === 'chat' && itm.userId === userInfo.id" :name="itm.nickname" :color="itm.color"
:text="itm.message"></my-message>
<text-message v-if="itm.type === 'chat' && itm.userId !== userInfo.id" :name="itm.nickname"
:text="itm.message" :color="itm.color"></text-message>
</li>
</ul>
</div>
<div class="input-box">
<div class="text">
<textarea :rows="8" v-model="message" @keydown="onKeydown"></textarea>
</div>
<div class="opt">
<a-button type="primary" ghost @click="sendMessage">发 送</a-button>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import MyMessage from './components/MyMessage.vue'
import TextMessage from './components/TextMessage.vue'
import fingerprint from '../utils/fingerprint'
import SystemMessage from './components/SystemMessage.vue'
interface IRecord {
nickname: string,
userId: string,
color: string,
type: string,
message: string,
sendTime: number
}
const getUserContent = () => {
const userId = fingerprint()
let name = localStorage.getItem(userId)
if (name) {
let color = localStorage.getItem('color' + userId)
color = color ? color : `rgba(${parseInt((Math.random() * 100 + 100).toString())},${parseInt((Math.random() * 100 + 100).toString())},${parseInt((Math.random() * 100 + 100).toString())},1)`
return {
id: userId,
name: name,
color: color
}
} else {
const randomName = ['苹果', '菠萝', '香蕉', '火龙果', '水蜜桃', '杨桃', '樱桃', '榴莲', '桔子', '葡萄', '荔枝', '哈密瓜']
name = randomName[parseInt((Math.random() * 12).toString())]
localStorage.setItem(userId, name)
const randomColor = `rgba(${parseInt((Math.random() * 100 + 100).toString())},${parseInt((Math.random() * 100 + 100).toString())},${parseInt((Math.random() * 100 + 100).toString())},1)`
localStorage.setItem('color' + userId, randomColor)
return {
id: userId,
name: name,
color: randomColor
}
}
}
const userInfo = ref(getUserContent())
const userCount = ref(1)
const records = ref<IRecord[]>([])
const recordsContent = ref<HTMLElement | null>()
const socket = new WebSocket("ws://10.2.127.75:3600")
socket.onopen = () => {
socket.send(JSON.stringify({
userId: userInfo.value.id,
nickname: userInfo.value.name,
color: userInfo.value.color,
type: 'system'
}))
}
socket.onmessage = (e) => {
let data = JSON.parse(e.data);
if (data.type === 'chatterList') {
let list = data.list;
userCount.value = list.length;
} else {
records.value.push(data as IRecord)
if (recordsContent.value) {
console.log(recordsContent.value.scrollHeight);
recordsContent.value.scrollTop = recordsContent.value.scrollHeight + 10
}
}
}
const message = ref('')
const onKeydown = (event: any) => {
if (event.keyCode === 13) {
sendMessage()
}
}
const sendMessage = () => {
if (message.value.trim()) {
socket.send(JSON.stringify({
userId: userInfo.value.id,
nickname: userInfo.value.name,
color: userInfo.value.color,
type: 'chat',
message: message.value
}))
message.value = ''
}
}
</script>
<style scoped lang="scss">
.chat-room {
margin: 0px auto;
width: 1000px;
height: 800px;
display: flex;
flex-direction: row;
.nav {
width: 66px;
background: #363636;
flex-shrink: 0;
}
.main {
display: flex;
background: #efefef;
flex: 1;
width: 0;
display: flex;
flex-direction: column;
.title {
height: 60px;
display: flex;
align-items: center;
font-size: 16px;
font-weight: 700;
padding-left: 20px;
border-bottom: 1px solid #c3c3c3;
flex-shrink: 0;
}
.content {
flex: 1;
height: 0px;
position: relative;
overflow: hidden;
ul {
list-style: none;
padding-left: 8px;
li {
margin-top: 14px;
}
}
}
.input-box {
height: 230px;
border-top: 1px solid #c3c3c3;
flex-shrink: 0;
display: flex;
flex-direction: column;
.text {
flex: 1;
textarea {
width: 100%;
height: 160px;
font-size: 16px;
resize: none;
border: none;
padding: 8px 24px;
background: #efefef;
&:focus {
outline: none;
}
&:focus-visible {
outline: none;
}
}
}
.opt {
height: 60px;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: flex-end;
padding-right: 20px;
}
}
}
}
</style>
细节与收获
- textarea点击确定按钮发送消息
const onKeydown = (event: any) => {
if (event.keyCode === 13) {
sendMessage()
}
}
- 浏览器指纹
浏览器指纹
- 滚动条插件封装指令
import PerfectScrollbar from 'perfect-scrollbar'
import 'perfect-scrollbar/css/perfect-scrollbar.css'
import { ObjectDirective } from 'vue'
const usePerfectScrollbar = () => {
let ps: null | PerfectScrollbar
const resize = () => {
ps && ps.update()
}
return {
install(el: Element | string) {
if (el) {
ps = new PerfectScrollbar(el, {
wheelSpeed: 2,
wheelPropagation: true,
scrollingThreshold: 100,
minScrollbarLength: 10
})
window.addEventListener('resize', resize, false)
return ps
}
},
uninstall() {
window.removeEventListener('resize', resize, false)
ps && ps.destroy()
}
}
}
const { install, uninstall } = usePerfectScrollbar()
const scrollbar: ObjectDirective = {
mounted(el: HTMLElement, b) {
install(el)
},
unmounted() {
uninstall()
}
}
export default scrollbar
- WebSocket的简单用法