Vue+express+Socket realizes chat function

Vue+express+Socket realizes chat function

This article shares the specific code of Vue+express+Socket to realize the chat function for your reference. The specific content is as follows

Implementing chat function

Specific functions

Just to realize the function, without beautifying the interface

1. Enter the message and click Send. All users can receive the message below.

2. Enter the userid and click Connect to connect to the corresponding chat. In another interface, enter the userid of the page just now, enter the content and click Send to the designated person. Then the page just now can be printed out, but other pages will not be received, realizing the function of private chat.

3. The content display of private chat is not specifically implemented, but receiving and sending messages can be implemented. To implement the content display of private chat, you can add another private chat page

Screenshots

Project Preparation

Only the socket preparation is introduced, and the construction of Vue and express is not introduced.

Front-end socket

Install

npm i vue-socket.io --save

Import

import VueSocketIO from 'vue-socket.io'

Background socket

Install

npm i socket.io --save

Import

Add to the bin/www folder produced by express-generator

var io = require('socket.io')(server)'
io.on('connection', (socket) => {
  socket.on('demining', (data) => {
    console.log(data);
  });
});

The specific screenshots are as follows:

Project realization

Vue Code

HTML Code

<div class="home">
    userid: <input type="text" v-model="userid">
    Nickname: <input type="text" v-model="name">
    Message: <input type="text" v-model="msg" />
    <button @click="send">Send</button>
    <button @click="join">Connect</button>
    <button @click="sendmsg">Send to specified person</button>

    <ul>
      <li v-for="(item,index) in chatList" :key="item.name + index">
        {{ item.name }} says: {{ item.msg }}
      </li>
    </ul>
</div>

js code

export default {
  name: "Home",
  data() {
    return {
      users: [],
      msg: "",
      chatList: [],
      name: '',
      userid: ''
    };
  },
  sockets: {
    // Connect to the background socket
    connect() {
      console.log('socket connected');
    },
    // User background call, add data sendMessage(data) {
      console.log(data);
      this.chatList.push(data)
    },
    // User background call, print data receivemsg(data) {
      console.log('receivemsg');
      console.log(data);
    }
  },
  methods: {
    // Send a message to the background send() {
      // Use emit to call the message method in the background socket this.$socket.emit("message", {
        userid: 100,
        name: this.name,
        msg: this.msg
      });
    },
    // Establish user connection join() {
      this.$socket.emit("join", {
        userid: this.userid
      });
    },
    // Send a message to the backend for private messaging sendmsg() {
      this.$socket.emit("sendmsg", {
        userid: this.userid,
        msg: this.msg
      });
    }
  }
};

express code

Add the following code to the connection defined in the www file just now

// Used to store each user's socket to implement private chat function let arrAllSocket = {}
// Create a socket connection io.on('connection', (socket) => {
  console.log('Connected');
  // console.log(socket);
  // The join function is used by users to connect socket.on('join', function (obj) {
    console.log(obj.userid + 'join')
    // Save the connection status of each user for private messaging arrAllSocket[obj.userid] = socket
  })
  // The function name for receiving messages sent by the foreground is message
  socket.on('message', (data) => {
    console.log(data);
    //Send the message back to the front desk (call the method defined in the front desk) The function name is sendMessage
    io.emit('sendMessage', data);
  });
  // Private message socket.on('sendmsg', function (data) {
    console.log(data);
    // Query user connection let target = arrAllSocket[data.userid]
    if (target) {
      //Send a message to the specified person target.emit('receivemsg', data)
    }
  })
})

Background code encapsulation

Since the www file should not have too much code, this part of the code is encapsulated

1. Create an io folder in the project directory with the following structure

2. Move the previous part of the code into io/index.js

The code is as follows

// Pass server as a parameter to module.exports = function (server) {
  var io = require('socket.io')(server);
// Used to store each user's socket to implement private chat function let arrAllSocket = {}
// Create a socket connection io.on('connection', (socket) => {
    console.log('Connected');
    // console.log(socket);
    // The join function is used by users to connect socket.on('join', function (obj) {
      console.log(obj.userid + 'join')
      // Save the connection status of each user for private messaging arrAllSocket[obj.userid] = socket
    })
    // The function name for receiving messages sent by the foreground is message
    socket.on('message', (data) => {
      console.log(data);
      //Send the message back to the front desk (call the method defined in the front desk) The function name is sendMessage
      io.emit('sendMessage', data);
    });
    // Private message socket.on('sendmsg', function (data) {
      console.log(data);
      // Query user connection let target = arrAllSocket[data.userid]
      if (target) {
        //Send a message to the specified person target.emit('receivemsg', data)
      }
    })
  })
}

Finally, use the following code in the www file to introduce the file

var io = require('../io')
io(server)

At this point, the basic functions of chatting are realized. Record it for later use.

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:
  • Vue implements chat interface
  • Vue realizes web online chat function
  • Vue+web terminal imitates WeChat web version chat room function
  • Vue.js imitates WeChat chat window to display component functions
  • Vue + socket.io implements a simple chat room sample code
  • A single-page application function imitating mobile QQ based on Vue2 (access to chatbot)
  • How to use RongCloud IM to implement chat function in Vue Cli 3 project
  • WeChat robot chat function example implemented by Vue [with source code download]
  • Multi-person online chat room based on vue and websocket
  • Vue+ssh framework to realize online chat

<<:  MySQL optimization strategy (recommended)

>>:  Detailed instructions for installing Jenkins on Ubuntu 16.04

Blog    

Recommend

JavaScript implements draggable modal box

This article shares the specific code of JavaScri...

Summary of 6 Linux log viewing methods

As a backend programmer, you deal with Linux in m...

Why can't the MP4 format video embedded in HTML be played?

The following code is in my test.html. The video c...

How to use selenium+testng to realize web automation in docker

Preface After a long time of reading various mate...

CSS3 realizes draggable Rubik's Cube 3D effect

Mainly used knowledge points: •css3 3d transforma...

Linux system to view CPU, machine model, memory and other information

During system maintenance, you may need to check ...

A bug fix for Tomcat's automatic shutdown

Preface Recently, a Java EE web project that has ...

Zabbix monitors Linux hosts based on snmp

Preface: The Linux host is relatively easy to han...

Example steps for using AntV X6 with Vue.js

Table of contents 0x0 Introduction 0x1 Installati...

js realizes two-way data binding (accessor monitoring)

This article example shares the specific code of ...

Basic reference types of JavaScript advanced programming

Table of contents 1. Date 2. RegExp 3. Original p...

Detailed process of installing and configuring MySQL and Navicat prenium

Prerequisite: Mac, zsh installed, mysql downloade...

JavaScript to implement the back to top button

This article shares the specific code for JavaScr...

A brief discussion on several ways to implement front-end JS sandbox

Table of contents Preface iframe implements sandb...