nodejs-websocket實(shí)現(xiàn)多人聊天室

效果圖

效果圖

邏輯分析

  1. 創(chuàng)建nodejs-websocket
  2. 根據(jù)消息類(lèi)型區(qū)分系統(tǒng)消息和普通消息
  3. 使用瀏覽器指紋來(lái)設(shè)置用戶(hù)信息(正常情況應(yīng)使用后端提供的用戶(hù)信息)
  4. 根據(jù)消息的userId顯示是誰(shuí)發(fā)的消息和自己發(fā)送的消息

核心代碼

const PORT = 3600


const ws = require('nodejs-websocket');

//封裝發(fā)送消息的函數(shù)(向每個(gè)鏈接的用戶(hù)發(fā)送消息)
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) => {
  //鏈接上來(lái)的時(shí)候
  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 + "進(jìn)入房間",
        }));

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

  //關(guān)閉鏈接的時(shí)候
  connect.on('close', () => {
    //離開(kāi)房間
    boardCast(JSON.stringify({
      type: 'system',
      message: connect.nickname + '離開(kāi)房間'
    }));

    //從在線(xiàn)聊天的人數(shù)上面除去
    boardCast(JSON.stringify({
      type: 'chatterList',
      list: getAllChatter()
    }))
  });

  //錯(cuò)誤處理
  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">發(fā) 送</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 = ['蘋(píng)果', '菠蘿', '香蕉', '火龍果', '水蜜桃', '楊桃', '櫻桃', '榴蓮', '桔子', '葡萄', '荔枝', '哈密瓜']
    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>

細(xì)節(jié)與收獲

  1. textarea點(diǎn)擊確定按鈕發(fā)送消息
const onKeydown = (event: any) => {
  if (event.keyCode === 13) {
    sendMessage()
  }
}
  1. 瀏覽器指紋

瀏覽器指紋

  1. 滾動(dòng)條插件封裝指令
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
  1. WebSocket的簡(jiǎn)單用法
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容