vue项目实现websocket

该博客详细介绍了如何在JavaScript中初始化WebSocket连接,包括错误处理、消息接收和发送。当连接建立后,它会发送一个测试消息,并在接收到响应时执行相应操作,如关闭加载提示、显示成功消息及重新获取表格数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        wsUrl: 'ws://1xxxxxxx:8099/imserver/9999', // ws地址
        websock: null, // ws实例
// 初始化weosocket
      initWebSocket() {

        if (typeof WebSocket === 'undefined')
          return console.log('您的浏览器不支持websocket')
        this.websock = new WebSocket(this.wsUrl)
        this.websock.onmessage = this.websocketonmessage
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onclose = this.websocketclose
      },
      websocketonopen() {
        // 连接建立之后执行send方法发送数据
        let actions = { test: 'test' }
        this.websocketsend(JSON.stringify(actions))
      },
      websocketonerror() {
        // 连接建立失败重连
        this.initWebSocket()
      },
      websocketonmessage(e) {
        console.log(e)
        // 数据接收
        const redata = JSON.parse(e.data)
        if (redata.code == 200) {
          this.fullscreenLoading = false
          this.rLoading.close();
          this.$message({
          message: 'xxxxxxxxxxxxxx!',
          type: 'success'
        });
          this.getTableData()
        } else {
          // this.initWebSocket()
        }
        console.log('接收的数据', redata)
      },
      websocketsend(Data) {
        // 数据发送
        this.websock.send(Data)
      },
      websocketclose(e) {
        // 关闭
        console.log('断开连接', e)
      },
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值