Vue uses WebSocket to simulate the chat function

Vue uses WebSocket to simulate the chat function

The effect shows that two browsers simulate each other

insert image description here

insert image description here

1. Create a simulated node service

Create a server.js file in the vue root directory to simulate the backend server

insert image description here

**Download in the server terminal directory**

npm install --s ws

2. Write the server.js file

The 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 npm run start to start the server

3.vue front-end page

The 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>
  1. 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! !
  2. The server prints logs when entering a chat room and sending messages

insert image description here

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:
  • How to use webSocket to update real-time weather in Vue
  • Example analysis of how Vue uses websocket
  • The process of using SockJS to implement webSocket communication in vue
  • The correct way to use websocket in vue project

<<:  ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

>>:  MySQL 8.0.13 installation and configuration graphic tutorial

Recommend

Front-end vue+express file upload and download example

Create a new server.js yarn init -y yarn add expr...

5 commonly used objects in JavaScript

Table of contents 1. JavaScript Objects 1).Array ...

Detailed explanation of ES6 Promise usage

Table of contents What is a Promise? Usage of rej...

Solution to the Docker container cannot be stopped and deleted

Find the running container id docker ps Find the ...

jQuery clicks on the love effect

This article shares the specific code of jQuery&#...

Problem record of using vue+echarts chart

Preface echarts is my most commonly used charting...

MySQL slow query pt-query-digest analysis of slow query log

1. Introduction pt-query-digest is a tool for ana...

CentOS7.5 installation tutorial of MySQL

1. First check whether the system has mysql insta...

Use Docker to build a Redis master-slave replication cluster

In a cluster with master-slave replication mode, ...

Summary of Linux file directory management commands

touch Command It has two functions: one is to upd...

Analysis of different MySQL table sorting rules error

The following error is reported when MySQL joins ...

Detailed analysis of compiling and installing vsFTP 3.0.3

Vulnerability Details VSFTP is a set of FTP serve...