This article shares the specific code of Vue+Websocket to simply implement the chat function for your reference. The specific content is as follows Effect picture: Chat Room This article is a simple understanding and application of Websocket , which is implemented by simply building a server using Nodejs . First create a vue project Then create a server folder, open the folder on the terminal, type vue init (keep pressing the "Enter" key), and finally create a server.js file, as shown below The code is as follows: server.js / In the server file terminal, run npm install --s ws 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 npm run start to start the server HelloWorld.vue (front-end page) <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) { // 192.168.0.115 is my local IP address. Here, the port number should be consistent with the backend configuration. let ws = new WebSocket("ws://192.168.0.115:8181"); _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; 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 is my local IP address (the default is localhost), you can change it to your own Then run npm run dev , and you can chat on the LAN. If you have wireless, you can use your mobile phone to connect to the wireless to access your IP address. If not, you can try opening a few more windows and you can see the effect! ! The server prints logs when entering a chat room and sending messages The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. You may also be interested in:
|
<<: Solve the problem that PhpStorm fails to connect to VirtualBox
>>: Mysql transaction isolation level principle example analysis
Experimental environment • A minimally installed ...
1. Install the database 1) yum -y install mysql-s...
Table of contents question Server layer and stora...
Many people say that IE6 does not support PNG tra...
The props of the component (props is an object) F...
Table of contents 1. BOM 2. Composition of BOM 2....
Preface Recently, I encountered a requirement at ...
Recently, I plan to deploy a cloud disk on my hom...
First, download the installation package from the...
(When a web page is loading, sometimes there is t...
Table of contents join algorithm The difference b...
When updating a record in MySQL, the syntax is co...
Preface NFS (Network File System) means network f...
1.1 Introduction to iptables firewall Netfilter/I...
1. Introduction As we all know, in the applicatio...