The effect shows that two browsers simulate each other 1. Create a simulated node service Create a **Download in the server terminal directory**
2. Write the server.js fileThe code is as follows var userNum = 0; //Count the number of online users var chatList = []; //Record chat history var WebSocketServer = require('ws').Server; wss = new WebSocketServer({ port: 8181 }); //8181 corresponds to the front end //Call broadcast to achieve data intercommunication and real-time update wss.broadcast = function (msg) { wss.clients.forEach(function each(client) { client.send(msg); }); }; wss.on('connection', function (ws) { userNum++; //Connection established successfully, number of people online +1 wss.broadcast(JSON.stringify({ funName: 'userCount', users: userNum, chat: chatList })); //Successful connection broadcasts the number of people currently online console.log('Connected clients:', userNum); //Receive data sent by the front end ws.on('message', function (e) { var resData = JSON.parse(e) console.log('Received a message from clent:' + resData.msg) chatList.push({ userId: resData.userId, content: resData.msg }); //Every time a message is sent, it will be stored and then broadcasted, so that each user who comes in can see the previous data wss.broadcast(JSON.stringify({ userId: resData.userId, msg: resData.msg })); //Each message sent is equivalent to broadcasting a message }); ws.on('close', function (e) { userNum--; //Establish connection and close the number of people online - 1 wss.broadcast(JSON.stringify({ funName: 'userCount', users: userNum, chat: chatList })); //Establish connection and close broadcast once. Current number of online clients console.log('Connected clients:', userNum); console.log('Long connection is closed') }) }) console.log('Server created successfully') Then 3.vue front-end pageThe code is as follows <template> <div class="chat-box"> <header>Number of people in chat room: {{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="contentText" @keyup.enter="sendText()" /> <div class="btn" :class="{['btn-active']:contentText}" @click="sendText()">Send</div> </div> </div> </template> <script> export default { data() { return { ws: null, count: 0, userId: null, //Current user ID list: [], //array of chat records contentText: "", //input value}; }, created() { this.getUserID(); }, mounted() { this.initWebSocket(); }, methods: { //Use the timestamp as the current user ID getUserID() { let time = new Date().getTime(); this.userId = time; }, //Generate a random avatar based on 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)); } }, //Scroll bar to the bottom scrollBottm() { let el = this.$refs["msg-box"]; el.scrollTop = el.scrollHeight; }, //Send chat message 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)); //Call WebSocket send() to send information _this.contentText = ""; setTimeout(() => { _this.scrollBottm(); }, 500); }, //Enter the page to create a websocket connection initWebSocket() { let _this = this; //Judge whether there is a websocket connection on the page if (window.WebSocket) { // The port number :8181 here should be consistent with the backend configuration let ws = new WebSocket("ws://192.168.5.42:9502"); // let ws = new WebSocket("ws://192.168.5.8:8181"); //Here is my local test_this.ws = ws; ws.onopen = function (e) { console.log("Server connection successful"); }; ws.onclose = function (e) { console.log("Server connection closed"); }; ws.onerror = function () { console.log("Server connection error"); }; ws.onmessage = function (e) { //Receive data returned by the server 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="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: 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>
This is the end of this article about how Vue uses WebSocket to simulate the chat function. For more relevant content about how Vue uses WebSocket to implement chat, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'
>>: MySQL 8.0.13 installation and configuration graphic tutorial
Create a new server.js yarn init -y yarn add expr...
Table of contents 1. JavaScript Objects 1).Array ...
Table of contents What is a Promise? Usage of rej...
MYSQL officially provides an Installer method to ...
Find the running container id docker ps Find the ...
This article shares the specific code of jQuery...
Mixin method: The browser cannot compile: The old...
Preface echarts is my most commonly used charting...
1. Introduction pt-query-digest is a tool for ana...
1. First check whether the system has mysql insta...
In a cluster with master-slave replication mode, ...
touch Command It has two functions: one is to upd...
The following error is reported when MySQL joins ...
Vulnerability Details VSFTP is a set of FTP serve...