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>
相关推荐
人工智能训练师4 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny074 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy5 小时前
css的基本知识
前端·css
昔人'5 小时前
css `lh`单位
前端·css
Nan_Shu_6147 小时前
Web前端面试题(2)
前端
知识分享小能手7 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队8 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
AD钙奶-lalala8 小时前
SpringBoot实现WebSocket服务端
spring boot·后端·websocket
孩子 你要相信光8 小时前
css之一个元素可以同时应用多个动画效果
前端·css
萌萌哒草头将军8 小时前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite