zoukankan      html  css  js  c++  java
  • 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));
      }
    }
    

     希望能帮助到大家!

      

  • 相关阅读:
    问题:charles开启Charles-Proxy-macOS Proxy 时报错
    通关中级测评师
    20210104 递归
    20201231-3 字符编码转换详解1
    20201231-2 元组
    20201231-1 购物车程序练习实例
    20201230-3 bytes数据类型
    20201230 python数据类型
    20201230 pyc是什么
    20201230-1 网络基础知识
  • 原文地址:https://www.cnblogs.com/jhy1016/p/12114377.html
Copyright © 2011-2022 走看看