Websocket+Vuex implements a real-time chat software

Websocket+Vuex implements a real-time chat software

Preface

This article mainly uses websocked to establish a long connection, uses the global communication characteristics of Vuex, and the watch and computed functions to monitor message changes and drive page changes to achieve real-time chat.

1. The effect is as shown in the figure

insert image description here

2. Specific implementation steps

1. Introducing Vuex

The code is as follows (example):

//Install vuex
npm install vuex

//Introduce in main.js import store from './store'
new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
})

I have made a simple encapsulation of Vuex, as shown in the figure below. You can proceed according to your own habits.

insert image description here

2.webscoked implementation

The webscoked implementation is mainly divided into the following parts:

Establishing a connection

Sending heartbeat packets

Reconnect after failure or error

const state = {
    url: '',
    webSocket: null,
    lockReconnect: false,
    messageList: [],
    msgItem: {},
    pingInterval: null,
    timeOut: null,
}
const mutations = {
    [types.INIT_WEBSOCKET](state, data) {
        state.webSocket = data
    },
    [types.LOCK_RE_CONNECT](state, data) {
        state.lockReconnect = data
    },
    [types.SET_PING_INTERVAL](state, data) {
        state.pingInterval = data
    },
    [types.SET_MSG_LIST](state, data) {
        state.messageList.push(data)
        state.msgItem = data
    },
}
const actions = {
  initWebSocket({ state, commit, dispatch, rootState }) {
        if (state.webSocket) {
            return
        }
        const realUrl = WSS_URL + rootState.doctorBasicInfo.token 
        const webSocket = new WebSocket(realUrl)
        webSocket.onopen = () => {
            console.log('Establish link');
            dispatch('heartCheck')
        }
        webSocket.onmessage = e => {
            console.log('Received message', e);
            try {
                if (typeof e.data === 'string' && e.data !== 'PONG') {
                    let res = JSON.parse(e.data)
                    console.log('Received content', res);
                    commit('SET_MSG_LIST', res)
                }
            } catch (error) {}
        }
        webSocket.onclose = () => {
            console.log('close');
            dispatch('reConnect')
        }
        webSocket.onerror = () => {
            console.log('failed');
            dispatch('reConnect')
        }

        commit('INIT_WEBSOCKET', webSocket)
    },
    // Heartbeat packet heartCheck({ state, commit }) {
        console.log(state, 'state');
        const { webSocket } = state
        const pingInterval = setInterval(() => {
            if (webSocket.readyState === 1) {
                webSocket.send('PING')
            }
        }, 20000)
        commit('SET_PING_INTERVAL', pingInterval)
    },
    //Reconnect reConnect({ state, commit, dispatch }) {
        if (state.lockReconnect) {
            return
        }
        commit('INIT_WEBSOCKET', null)
        commit('LOCK_RE_CONNECT', true)
        setTimeout(() => {
            dispatch('initWebSocket')
            commit('LOCK_RE_CONNECT', false)
        }, 20000)
    },
 }
const getters = {
    webSocket: state => state.webSocket,
    messageList: state => state.messageList,
    msgItem: state => state.msgItem,
}
export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}

Page Fetch

methods: {
...mapActions("webSocket", ["initWebSocket", "close"]),
   pushItem(item) {
      const initMsg = item;
      this.msgList.push(initMsg);
    }
}
mounted() {
	this.initWebSocket();
}
watch:
    msgItem: function (item) {
        this.pushItem(item);
    }
  },
computed: {
    ...mapGetters("webSocket", ["messageList", "msgItem"]),
   
  },

UI

 <li v-for="(item, i) in msgList" :key="i" class="msgBox"></li>

Explanation of webscoked implementation ideas

1. First create a ws link in actions.

2. Use the watch attribute to monitor the corresponding message changes in the state on the page. When a new message is received, change the message list displayed on the page and use two-way binding to achieve automatic page updates.

3. When sending a message, call the backend interface and insert the new message into the message list displayed on the page

4. Because ws is a long link that will not be easily disconnected once established, as long as the message pushed by the backend is received and it is determined whether there is message content, when there is message content, you only need to change the message list in the state, and the page will be automatically updated according to the watch attribute, perfectly realizing the instant messaging function.

Summarize

This is the end of this article about implementing a real-time chat software with websocket+Vuex. For more relevant websocket+Vuex real-time chat content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue+Websocket simply implements the chat function
  • Vue uses WebSocket to simulate the chat function
  • Vue + WebSocket + WaveSurferJS to implement H5 chat dialogue interaction example
  • Implementing simple WebSocket chat function based on node+vue
  • Multi-person online chat room based on vue and websocket
  • 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
  • Vue implements websocket customer service chat function

<<:  How to use the Linux basename command

>>:  Causes and solutions for slow MySQL query speed and poor performance

Recommend

About deploying a web project to Alibaba Cloud Server (5 steps to do it)

1. First log in to the Alibaba Cloud website to r...

Vue custom directive details

Table of contents 1. Background 2. Local custom i...

Source code reveals why Vue2 this can directly obtain data and methods

Table of contents 1. Example: this can directly g...

Tutorial on installing MySQL database and using Navicat for MySQL

MySQL is a relational database management system ...

MySQL Query Cache Graphical Explanation

Table of contents 1. Principle Overview Query Cac...

React Diff Principle In-depth Analysis

Table of contents Diffing Algorithm Layer-by-laye...

Detailed explanation of Linux rpm and yum commands and usage

RPM package management A packaging and installati...

Alibaba Cloud Ubuntu 16.04 builds IPSec service

Introduction to IPSec IPSec (Internet Protocol Se...

React tips teach you how to get rid of hooks dependency troubles

A very common scenario in react projects: const [...

A brief discussion on MySQL index optimization analysis

Why are the SQL queries you write slow? Why do th...

Docker advanced method of rapid expansion

1. Command method Run the nginx service in the cr...

Recommend some useful learning materials for newbies in web design

Many people also asked me what books I read when ...