webcoket推送链接

该段代码展示了在Vue.js中如何初始化并使用WebSocket进行通信。当WebSocket连接打开时,向服务器发送数据;如果连接出现错误,则尝试重新连接;接收到服务器消息时进行处理,并在组件销毁时关闭WebSocket连接。
摘要由CSDN通过智能技术生成
<template>
  <div class="test">
  </div>
</template>

<script>
  export default {
    data() {
      return {
        websock: null,
      }
    },
    methods: {
      // 初始化weosocket
      initWebSocket(){ 
        if(typeof(WebSocket) === "undefined"){
          console.log("您的浏览器不支持WebSocket")
        }else{
          const wsurl = "ws://192.168.0.29:10052/vehicle-location";
          // 实例化 WebSocket
          this.websock = new WebSocket(wsurl);
          // 监听 WebSocket 连接
          this.websock.onopen = this.websocketonopen;
          // 监听 WebSocket 错误信息
          this.websock.onerror = this.websocketonerror;
          // 监听 WebSocket 消息
          this.websock.onmessage = this.websocketonmessage;
        
          this.websock.onclose = this.websocketclose;
        }
      },
      // 连接建立之后执行send方法发送数据
      websocketonopen(){
        console.log("socket连接成功")
        let actions = {"hxw":"是我男神"};
        this.websocketsend(JSON.stringify(actions));
      },
      // 连接建立失败重连
      websocketonerror(){
        console.log("连接错误");
        this.initWebSocket();
      },
      // 数据接收
      websocketonmessage(e){
        const resdata = e.data
        // console.log(e);
        // console.log(resdata);
      },
      // 数据发送
      websocketsend(Data){
        this.websock.send(Data);
      },
      // 关闭
      websocketclose(e){
        console.log('WebSocket 断开连接',e);
      },
    },    
    beforeMount() {
      this.initWebSocket();
    },
    destroyed() {
      //离开路由之后断开 websocket 连接
      this.websock.close(); 
    },
  }
</script>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值