Vue封装websocket双向通讯

  1. 封装的socket.js文件内容:

    var websock = null;

    var global_callback = null;
    var serverPort = '80'; // webSocket连接端口
    var wsuri = 'wss://uat.sssyin.cn/ws-reservation';

    function createWebSocket(callback) {

    if (websock == null || typeof websock !== WebSocket) {
    initWebSocket(callback);
    }
    }

    function initWebSocket(callback) {
    global_callback = callback;
    // 初始化websocket
    websock = new WebSocket(wsuri);
    websock.onmessage = function (e) {
    websocketonmessage(e);
    };
    websock.onclose = function (e) {
    websocketclose(e);
    };
    websock.onopen = function () {
    websocketOpen();
    };

    // 连接发生错误的回调方法
    websock.onerror = function () {
    console.log('WebSocket连接发生错误');
    //createWebSocket();啊,发现这样写会创建多个连接,加延时也不行
    };
    }

    // 实际调用的方法
    function sendSock(agentData ) {

    if (websock.readyState === websock.OPEN) {
    // 若是ws开启状态
    websocketsend(agentData);
    } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态,则等待1s后重新调用
    setTimeout(function () {
    sendSock(agentData);
    }, 1000);
    } else {
    // 若未开启 ,则等待1s后重新调用
    setTimeout(function () {
    sendSock(agentData);
    }, 1000);
    }
    }

    function closeSock() {
    websock.close();
    }

    // 数据接收
    function websocketonmessage(msg) {
    // console.log("收到数据:"+JSON.parse(e.data));
    // console.log("收到数据:"+msg);

    // global_callback(JSON.parse(msg.data));

    // 收到信息为Blob类型时
    let result = null;
    // debugger
    if (msg.data instanceof Blob) {
    const reader = new FileReader();
    reader.readAsText(msg.data, 'UTF-8');
    reader.onload = e => {
    result = JSON.parse(reader.result);
    //console.log("websocket收到", result);
    global_callback(result);
    };
    } else {
    result = JSON.parse(msg.data);
    //console.log("websocket收到", result);
    global_callback(result);
    }
    }

    // 数据发送
    function websocketsend(agentData) {
    console.log(发送数据:${ agentData });
    websock.send(agentData);
    }

    // 关闭
    function websocketclose(e) {
    console.log(connection closed (${ e.code }));
    }

    function websocketOpen(e) {
    console.log('连接打开');
    }

    export { sendSock, createWebSocket, closeSock };

2、页面调用

复制代码
<template>
  <div>
    <button>发消息</button>
  </div>
</template>

<script>
import { sendSock, createWebSocket, closeSock } from './sockt.js';

export default {
  data () {
    return {

    }
  },
  created() {
    this.init();
  },
  destroyed(){
    closeSock();
  },
  methods: {
    init() {
      createWebSocket(this.global_callback);

    },
    send(){
      var sendData = {
        operate:'singleChannelSwitch',
        index:index+1,
        opera:row.button_relay
      };
      sendSock(1111);
    },
    // websocket的回调函数,msg表示收到的消息
    global_callback(msg) {
      console.log(`websocket的回调函数收到服务器信息:${ JSON.stringify(msg) }`);
      // console.log("收到服务器信息:" + msg);
    },
  }
}
</script>

<style>

</style>
相关推荐
Captaincc24 分钟前
AI 能帮你写代码,但把代码变成软件,还是得靠人
前端·后端·程序员
程序员杨工27 分钟前
【原创】SpringBoot3+Vue3客户管理系统
vue.js·springboot
吃饺子不吃馅2 小时前
如何设计一个 Canvas 事件系统?
前端·canvas·图形学
theOtherSky2 小时前
element+vue3 table上下左右键切换input和select
javascript·vue.js·elementui·1024程序员节
Baklib梅梅2 小时前
无头内容管理系统:打造灵活高效的多渠道内容架构
前端·ruby on rails·前端框架·ruby
over6972 小时前
浏览器里的AI魔法:用JavaScript玩转自然语言处理
前端·javascript
渣渣盟3 小时前
探索Word2Vec:从文本向量化到中文语料处理
前端·javascript·python·文本向量化
Pu_Nine_93 小时前
Vue 3 + TypeScript 项目性能优化全链路实战:从 2.1MB 到 130KB 的蜕变
前端·vue.js·性能优化·typescript·1024程序员节
云枫晖3 小时前
Webpack系列-Loader
前端·webpack
aggression3 小时前
代码敲击乐:让你了解前端的动静结合和移动端的适配性
前端