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

Summary of 10 must-see JavaScript interview questions (recommended)

1.This points to 1. Who calls whom? example: func...

How to configure ssh/sftp and set permissions under Linux operating system

Compared with FTP, SSH-based sftp service has bet...

Bootstrap realizes the effect of carousel

This article shares the specific code of Bootstra...

Detailed explanation of the principle and function of Vue list rendering key

Table of contents The principle and function of l...

How to Run a Command at a Specific Time in Linux

The other day I was using rsync to transfer a lar...

Implementation of React virtual list

Table of contents 1. Background 2. What is a virt...

Summary of a CSS code that makes the entire site gray

In order to express the deep condolences of peopl...

Tutorial on installing lamp-php7.0 in Centos7.4 environment

This article describes how to install lamp-php7.0...

How to draw a vertical line between two div tags in HTML

Recently, when I was drawing an interface, I enco...

JavaScript to achieve text expansion and collapse effect

The implementation of expanding and collapsing li...

How does Vue3's dynamic components work?

Table of contents 1. Component Registration 1.1 G...

WeChat Mini Programs Implement Star Rating

This article shares the specific code for WeChat ...

Solution to Tomcat server failing to open tomcat7w.exe

I encountered a little problem when configuring t...

Table related arrangement and Javascript operation table, tr, td

Table property settings that work well: Copy code ...