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

Recommend

Innodb system table space maintenance method

Environmental Description: There is a running MyS...

Summary of HTML knowledge points for the front end (recommended)

1. HTML Overview htyper text markup language Hype...

Vue song progress bar sample code

Note that this is not a project created by vue-cl...

The final solution to Chrome's minimum font size limit of 12px

I believe that many users who make websites will ...

Solution to garbled display of Linux SecureCRT

Let's take a look at the situation where Secu...

Steps to install GRUB on Linux server

How to Install GRUB for Linux Server You cannot u...

Tutorial on importing and exporting Docker containers

background The popularity of Docker is closely re...

Web designers also need to learn web coding

Often, after a web design is completed, the desig...

jQuery implements all selection and reverse selection operation case

This article shares the specific code of jQuery t...

Detailed Tutorial on Installing VirtualBox 6.0 on CentOS 8 / RHEL 8

VirtualBox is a free and open source virtualizati...

JavaScript basics of this pointing

Table of contents this Method In the object Hidde...

How MySQL handles implicit default values

Some students said that they encountered the prob...