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

Pure CSS to achieve candle melting (water droplets) sample code

Achieve results Implementation ideas The melting ...

How to add automatic completion commands for docker and kubectl on Mac

Introduction to kubectl kubectl is a command line...

React Router V6 Updates

Table of contents ReactRouterV6 Changes 1. <Sw...

Linux system MySQL8.0.19 quick installation and configuration tutorial diagram

Table of contents 1. Environment Introduction 2. ...

MySQL index principle and query optimization detailed explanation

Table of contents 1. Introduction 1. What is an i...

Detailed explanation of the difference between CSS link and @import

How to add css in html? There are three ways to s...

Website front-end performance optimization: JavaScript and CSS

I have read an article written by the Yahoo team ...

Docker deployment of Flask application implementation steps

1. Purpose Write a Flask application locally, pac...

Summary of JavaScript custom object methods

Table of contents 1. Use object to create an obje...

Optimized implementation of count() for large MySQL tables

The following is my judgment based on the data st...

Native JS encapsulation vue Tab switching effect

This article example shares the specific code of ...

Vue2.0 implements adaptive resolution

This article shares the specific code of Vue2.0 t...

Nginx Linux installation and deployment detailed tutorial

1. Introduction to Nginx Nginx is a web server th...