WebSocket基本操作步骤

本文展示了在Vue3中如何建立WebSocket连接,处理各种事件如开启、接收消息、关闭及错误,并提供了发送数据到后端的示例。同时提到了Vue2中使用代理的方式以及需要引入`getCurrentInstance`获取proxy。

首先需要与后台搭建连接

// vue3写法 如果是vue2 请把proxy换成this
const openWebScoket = () => {
    if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        let socketUrl = `${hostWeb}/websocket/` + info.sc.uuid;
        socketUrl = socketUrl
            .replace("https", "wss")
            .replace("http", "ws");
        proxy.websocket = new WebSocket(socketUrl);
        //打开事件
        proxy.websocket.onopen = function (msg) {
            console.log("开启scoket连接成功");
        };
        //获得消息事件
        proxy.websocket.onmessage = function (msg) {
       	 // msg是从后端拿的值 根据情况做一下数据处理
            let res = JSON.parse(msg.data);

		// 这里写你自己的业务逻辑
		.....
          
        }
        //关闭事件
        proxy.websocket.onclose = function (msg) {
            console.log("websocket已关闭", msg);

        };
        //发生了错误事件
        proxy.websocket.onerror = function (msg) {
            console.log("websocket发生了错误", msg);
        };
    }
}


const getOK = (item) => {
 
    if (typeof WebSocket == "undefined") {
          ElMessage.warning("您的浏览器不支持WebSocket");
      } else {
      //哪里用到了websocket就在哪里调用,下面是后端需要的参数
         proxy.websocket.send(
            JSON.stringify({
                uuid: info.sc.uuid,
                type: 'openTemplate',
                 templateUrl: fileUrl
            })
     );
    }
  }

如果你使用的vue3,记得引入proxy

<script setup>
import {  getCurrentInstance} from 'vue';
const { proxy } = getCurrentInstance();
</script>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值