1. 程式人生 > 程式設計 >vue使用WebSocket模擬實現聊天功能

vue使用WebSocket模擬實現聊天功能

效果展示 兩個瀏覽器相互模擬

在這裡插入圖片描述

在這裡插入圖片描述

1.建立模擬node服務

在根目錄下建立 server. 檔案模擬後端伺服器

在這裡插入圖片描述

**在server終端目錄下載 **

npm install --s ws

2.編寫server.js檔案

程式碼如下

var userNum = 0; //統計線上人數
var chatList = [];//記錄聊天記錄
var WebSocketServer = require('ws').Server;
wss = new WebSocketServer({ port: 8181 }); //8181 與前端相對應
//呼叫 broadcast 廣播,實現資料互通和實時更新
wss.broadcast = function (msg) {
    wss.clients.forEach(function each(client) {
        client.send(msg);
    });
};
wss.on('connection',function (ws) {
    userNum++;//建立連線成功線上人數 +1
    wss.broadcast(JSON.stringify({ funName: 'userCount',users: userNum,chat: chatList })); //建立連線成功廣播一次當前線上人數
    console.log('Connected clients:',userNum);
    //接收前端傳送過來的資料
    ws.on('message',function (e) {
        var resData = JSON.parse(e)
        console.log('接收到來自clent的訊息:' + resData.msg)
        chatList.push({ userId: resData.userId,content: resData.msg });//每次傳送資訊,都會把資訊存起來,然後通過廣播傳遞出去,這樣此每次進來的使用者就能看到之前的資料
        wss.broadcast(JSON.stringify({ userId: resData.userId,msg: resData.msg })); //每次傳送都相當於廣播一次訊息

    });
    ws.on('close',function (e) {
        userNum--;//建立連線關閉線上人數 -1
        wss.broadcast(JSON.stringify({ funName: 'userCount',chat: chatList }));//建立連線關閉廣播一次當前線上人數
        console.log('Connected clients:',userNum);
        console.log('長連線已關閉')
    })
})
console.log('伺服器建立成功')

然後npm run start啟動伺服器

3.vue前端頁面

程式碼如下

<template>
  <div class="chat-box">
    <header>聊天室人數:{{count}}</header>
    <div class="msg-box" ref="msg-box">
      <div
        v-for="(i,index) in list"
        :key="index"
        class="msg"
        :style="i.userId == userId?'flex-direction:row-reverse':''"
      >
        <div class="user-head">
          <div
            class="head"
            :style="` background: hsl(${getUserHead(i.userId,'bck')},88%,62%); clip-path:polygon(${getUserHead(i.userId,'polygon')}% 0,100% 100%,0% 100%); transform: rotate(${getUserHead(i.userId,'rotate')}deg)`"
          ></div>
        </div>
        <div class="user-msg">
          <span
            :style="i.userId == userId?'float: right':''"
            :class="i.userId == userId?'right':'left'"
          >{{i.content}}</span>
        </div>
      </div>
    </div>
    <div class="input-box">
      <input type="text" ref="sendMsg" v-model="conten
tText" @keyup.enter="sendText()" /> <div class="btn" :class="{['btn-active']:contentText}" @click="sendText()">傳送</div> </div> </div> </template> <script> export default { data() { return { ws: null,count: 0,userId: null,//當前使用者ID list: [],//聊天記錄的陣列 contentText: "",//input輸入的值 }; },www.cppcns.com
created() { this.getUserID(); },mounted() { this.initWebSocket(); },methods: { //根據時間戳作為當前使用者ID getUserID() { let time = new Date().getTime(); this.userId = time; },//根據userID生成一個隨機頭像 getUserHead(id,type) { let ID = String(id); if (type == "bck") { return Number(ID.substring(ID.length - 3)); } if (type == "polygon") { return Number(ID.substring(ID.length - 2)); } if (type == "rotate") { return Number(ID.substring(ID.length - 3)); } },//滾動條到底部 scrollBottm() { let el = this.$refs["msg-box"]; el.scrollTop = el.scrollHeight; },//傳送聊天資訊 sendText() { let _this = this; _this.$refs["sendMsg"].focus(); if (!_this.contentText) { return; } let params = { userId: _this.userId,msg: _this.contentText,}; _this.ws.send(JSON.stringify(params)); //呼叫WebSocket send()傳送資訊的方法 _this.contentText = ""; setTimeout(() => { _this.scrollBottm(); },500); },//進入頁面建立websocket連線 initWebSocket() { let _this = this; //判斷頁面有沒有存在websocket連線 if (window.WebSocket) { // 此處的 :8181 埠號 要與後端配置的一致 let ws = new WebSocket("ws://192.168.5.42:9502"); // let ws = new WebSocket("ws://192.168.5.8:8181"); //這裡是我本地測試 _this.ws = ws; ws.onopen = function (e) { console.log("伺服器連線成功"); }; ws.onclose = function (e) { console.log("伺服器連線關閉"); }; ws.onerror = function () { console.log("伺服器連接出錯"); }; ws.onmessage = function (e) { //接收伺服器返回的資料 let resData = JSON.parse(e.data); if (resData.funName == "userCount") { _this.count = resData.users; _this.list = resData.chat; } else { _this.list = [ ..._this.list,{ userId: resData.userId,content: resData.msg },]; } }; } },},}; </script> <style lang="s" scoped> .chat-box { margin: 0 auto; background: #fafafa; position: absolute; height: 100%; width: 100%; // max-width: 700px; header { position: fixed; width: 100%; height: 3rem; background: #409eff; // max-width: 700px; display: flex; justify-content: center; align-items: center; font-weight: bold; color: white; font-size: 1rem; } .msg-box { position: absolute; height: calc(100% - 6.5rem); width: 100%; margin-top: 3rem; overflow-y: scroll; .msg { width: 95%; min-height: 2.5rem; margin: 1rem 0.5rem; position: relative; display: flex; justify-content: flex-start !important; .user-head { min-width: 2.5rem; width: 20%; width: 2.5rem; height: 2.5rem; border-radius: 50%; background: #f1f1f1; display: flex; justify-content: center; align-items: center; .head { width: 1.2rem; height: 1.2rem; } // position: absolute; } .user-msg { width: 80%; // position: absolute; word-break: break-all; position: relative; z-index: 5; span { display: inline-block; padding: 0.5rem 0.7rem; border-radius: 0.5rem; margin-top: 0.2rem; font-size: 0.88rem; } .left { background: white; animation: toLeft 0.5s ease both 1; } .right { background: #53a8ff; color: white; animation: toright 0.5s ease both 1; } @keyframes toLeft { 0% { opacity: 0; transform: translateX(-10px); } 100% { opacity: 1; transform: translateX(0px); } } @keyframes toright { 0% { opacity: 0; transform: translateX(10px); } 100% { opacity: 1; transform: translateX(0px); } } } } } .input-box { padding: 0 0.5rem; position: absolute; bottom: 0; width: 97%; height: 3.5rem; background: #fafafa; box-shadow: 0 0 5px #ccc; display: flex; justify-content: space-between; align-items: center; input { height: 2.3rem; display: inline-block; width: 100%; padding: 0.5rem; border: none; border-radius: 0.2rem; font-size: 0.88rem; } .btn { height: 2.3rem; min-width: 4rem; background: #e0e0e0; padding: 0.5rem; font-size: 0.88rem; color: white; text-align: center; border-radius: 0.2rem; margin-left: 0.5rem; transition: 0.5s; line-height: 2.3rem; } .btn-active { background: #409eff; } } } </style>
  1. 然後npm run dev,就可以實現區域網聊天了,有無線的話可以用手機連著無線訪問你的IP地址訪問,沒的話可以試下多開幾個視窗,也是能看到效果的!!
  2. 進入聊天室時和傳送資訊時伺服器的列印日誌

在這裡插入圖片描述

到此這篇關於vue使用WebSocket模擬實現聊天功能的文章就介紹到這了,更多相關vue使用WebSocket實現聊天內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!