• vue项目使用websocket做聊天,断开连接及刷新重连


    一、首先我们先了解一下websocket的使用:

    1、创建websocket

    const ws = new WebSocket("ws://192.168.31.136:9998/ws");

    2、已连接上,使用 send() 方法发送用户信息给后端

    ws.onopen = ()=>{

       ws.send("发送数据");

    }

    3、收到消息

    ws.onmessage=(evt)=>{

      var received_msg = evt.data;

    }

    4、连接断开

    ws.onclose=(evt)=>{

      console.log(evt)  

    }

    二、vue项目使用websocket思路.

    1、登录成功后连接websocket。

        为了防止刷新页面后websocket会断开连接,我们在main.js中添加如下代码。

    import Vue from "vue";
    import App from "./App.vue";
    import router from "./router";
    import store from "./store";
    import { initWebSocket } from "./plugins/socket";
    try {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      if (userInfo) {
        store.commit("setUserInfo", userInfo);
        initWebSocket();
      }
    } catch (error) {
      console.log(error);
    }
    Vue.config.productionTip = false;
    new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount("#app");
    

      

    2、收到消息后保存到vuex state状态中

    3、聊天页面监听vuex state数据。

    4、push进聊天记录数组。

    以下是我简单封装的websocket方法:

    import vuex from "../store";
    let ws = null;
    export function initWebSocket() {
      let userInfo = vuex.state.userInfo;
      // 创建websocket
      ws = new WebSocket("ws://192.168.31.141:5566/ws");
      // 连接成功发送用户信息给后端
      ws.onopen = function() {
        let msg = {
          token: userInfo.token,
          type: 1,
          msgType: 0,
          sendUserId: userInfo.id
        };
        ws.send(JSON.stringify(msg));
      };
      // 收到消息保存到vuex
      ws.onmessage = function(event) {
        vuex.commit("setMsg", event.data);
        console.log(event);
      };
      // 断开连接后进行重连
      ws.onclose = function(event) {
        console.log(event);
        let userInfo = vuex.state.userInfo;
        if (userInfo) {
          setTimeout(() => {
            initWebSocket();
          }, 5000);
        }
      };
    }
    // 发送消息(可以引入使用,也可以挂在到Vue原型上面使用)
    export function webSocketSend(data) {
      if (ws.readyState === 1) {
        ws.send(JSON.stringify(data));
      }
    }
    

     希望能帮助到大家!

      

  • 相关阅读:
    QlikView TEXT控件固定显示图片
    Qlikview List控件
    如何实现Qlikview的增量数据加载
    SQL Server开启READ_COMMITTED_SNAPSHOT
    AX函数,将EXCEL列号转为列名
    C# 中DataGridView 绑定List<T>做数据源的操作问题
    Could not resolve this reference. Could not locate the assembly
    WinForm程序用使用List对象绑定DataGridView数据源
    C#WebBrowser控件使用教程与技巧收集
    python局部变量、全局变量,global、nolocal的区别
  • 原文地址:https://www.cnblogs.com/jhy1016/p/12114377.html
Copyright © 2020-2023  润新知