js websocket的使用

该文描述了一个WebSocket连接的实现过程,包括连接、重连机制、消息收发以及心跳检测。使用uni-app的uni.connectSocket方法建立WebSocket连接,并在连接成功、接收到消息、发生错误或关闭时进行相应的处理。此外,还封装了一个支持Promise和回调的WebSocket函数。

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

//连接websocket
            connectSocket() {
                let that = this;
                console.log('调用连接websocket', `ws://172.16.1.152:11576/webSocket`)
                this.socketTask = uni.connectSocket({
                        url: 'ws://172.16.1.152:11576/webSocket',
                        success(res) {
                            console.log("websocket连接成功");
                            // that.isSuccess = true
                        },
                        fail(err) {
                            console.log("报错", err);
                        }
                    },
                );
                this.socketTask.onOpen(function(res) {
                    console.log('WebSocket连接已打开!');
                    that.isSuccess = true
                })
                this.socketTask.onMessage(function(res) {
                    console.log('收到服务器内容:' + res.data);
                    if(res.data == '1') {
                        // 刷新伙食费分析数据
                        this.$refs['analysisExpenses'].getExpensesAnalysisShow();
                    }
                    // that.handlerMsg(JSON.parse(res.data)) //这里是对获取到的数据进行操作
                });
                this.socketTask.onError(function(res) {
                    console.log('WebSocket连接打开失败,请检查!');
                    console.log(res);
                    // this.isSuccess = false
                    this.connectSocket();
                    //进入重新连接
                    that.reconnect();
                })
                // // 监听连接关闭 -
                this.socketTask.onClose((e) => {
                    console.log('WebSocket连接关闭!');
                    clearInterval(that.timer)
                    that.timer = ''
                    if (!that.isClose) {
                        that.reconnect()
                    }
                })
                console.log(this.socketTask)
            },
            //进入重新连接
            reconnect() {
                console.log('进入断线重连');
                // this.socketTask.close();
                this.socketTask = null;
                this.connectSocket()
            
            },
            //发送消息
            sendSocketMessage(msg) {
                console.log('发送信息')
                console.log(msg)
                return new Promise((reslove, reject) => {
                    this.socketTask.send({
                        data: msg,
                        success(res) {
                            console.log('发送成功')
                            reslove(res)
                        },
                        fail(res) {
                            console.log('发送失败')
                            console.log(res)
                            reject(res)
                        }
                    });
                })
            },
            // 心跳
            heart() {
                let that = this;
                clearInterval(this.timer);
                this.timer = '';
                let msg = {
                    "type": "heartbeat",
                }
                this.timer = setInterval(() => {
                    that.sendSocketMessage(JSON.stringify(msg)).then(res => {
                        console.log('心跳成功')
                    }).catch(res => {
                        console.log('发送失败')
                        console.log((res))
                    })
                }, 200000)
            },

封装webSocket

/**
 * 注册websocket
 * @mask 支持promise返回,也支持回调返回
 * @param path websocket地址
 * @param onMsg  接收推送的回调函数
 * @param onOpen 连接消息
 * @param onErr 错误消息
 * @returns {Promise}
 */
export function websocket(opt = {
  path: '', onMsg: () => {
  }, onOpen: () => {
  }, onErr: () => {
  }
}) {
  return new Promise((resolve, reject) => {
    console.log(opt.path);
    try {
      let ws = new WebSocket(opt.path)
      let heartTimer
      // 绑定消息
      ws.onmessage = (msg) => {
        if (msg.data !== 'heart') { // 非心跳包返回
          if (opt.onMsg) opt.onMsg(msg, ws)
          resolve(msg, ws);
        }
      }

      ws.onopen = (event) => { // 绑定连接消息
        if (opt.onOpen) opt.onOpen(event, ws);
        heartTimer = setInterval(() => { // 连接成功后发2秒心跳包
          ws.send('heart')
        }, 2000)
      }

      ws.onerror = (err) => { // 绑定错误消息
        console.log(err);
        if (opt.onErr) opt.onErr(err, ws)
        reject(err, ws);
        clearTimeout(heartTimer)
      }
      ws.onclose = () => {
        ws.close();
        clearTimeout(heartTimer)
      }
    } catch (e) {
      console.log(e);
      reject();
    }
  })
}

export default websocket;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩召华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值