您好,登錄后才能下訂單哦!
小編給大家分享一下Vue+Websocket如何實現聊天功能,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
具體內容如下
效果圖:
聊天室
此篇文章是針對Websocket的簡單了解和應用,利用Nodejs簡單搭建一個服務器加以實現。
首先創建一個vue項目
然后再創建一個server文件夾,在終端上打開該文件夾,輸入vue init(一直敲 "回車" 鍵),最后再建一個server.js文件,如下圖
代碼如下:
server.js/
在server文件終端下 npm install --s ws
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', users: userNum, chat: chatList }));//建立連接關閉廣播一次當前在線人數 console.log('Connected clients:', userNum); console.log('長連接已關閉') }) }) console.log('服務器創建成功')
然后npm run start啟動服務器
HelloWorld.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" : > <div class="user-head"> <div class="head" : ></div> </div> <div class="user-msg"> <span : :class="i.userId == userId?'right':'left'" >{{i.content}}</span> </div> </div> </div> <div class="input-box"> <input type="text" ref="sendMsg" v-model="contentText" @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輸入的值 }; }, 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) { // 192.168.0.115 是我本地IP地址 此處的 :8181 端口號 要與后端配置的一致 let ws = new WebSocket("ws://192.168.0.115: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; console.log(resData.chat); } else { _this.list = [ ..._this.list, { userId: resData.userId, content: resData.msg } ]; } }; } } } }; </script> <style lang="scss" 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: 100%; 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; } .btn-active { background: #409eff; } } } </style>
192.168.0.115是我本地的IP地址(默認是 localhost ),你可以改成你自己的
然后npm run dev,就可以實現局域網聊天了,有無線的話可以用手機連著無線訪問你的IP地址訪問,?沒的話可以試下多開幾個窗口,也是能看到效果的!!
進入聊天室時和發送信息時服務器的打印日志
以上是“Vue+Websocket如何實現聊天功能”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。