vue和小程序实现webSocket双向实时通信

本文介绍了如何在Vue和微信小程序中利用WebSocket技术实现高效的实时通信,包括WebSocket连接的建立、数据接收和错误处理等关键步骤。

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

前言:以前前端实现实时通信都是用的ajax轮询,效率低、耗资源。通过webSocket技术可以完美解决这个问题

一、简介

webSocket连接服务器的URI以“ws”或者“wss”开头。webSocket 在浏览器和服务器完成一个握手的动作,在建立连接之后,服务器可以主动传送数据给客户端,客户端也可以随时向服务器发送数据。

二、vue实现

// 初始化webSocket
initWebSocket (userId) { 
    const wsuri = 'ws://117.62.22.237:9131/business/internal/webSocket/' + userId
    this.websock = new WebSocket(wsuri)
    this.websock.onmessage = this.websocketonmessage
    this.websock.onopen = this.websocketonopen
    this.websock.onerror = this.websocketonerror
    this.websock.onclose = this.websocketclose
},

// 连接建立之后执行send方法发送数据
websocketonopen () { 
  // let actions = {'test': '12345'}
  // this.websocketsend(JSON.stringify(actions))
},

// 连接建立失败重连
websocketonerror () { 
    this.initWebSocket()
},

// 数据接收
websocketonmessage (e) { 
    const redata = JSON.parse(e.data)
    // todo
},

// 关闭
websocketclose (e) { 
    console.log('断开连接', e)
}

1)在需要的地方this.initWebSocket(),没有参数可以不传

2)wsuri为后台提供给你的地址

3)在websocketonmessage()方法获取返回的数据并进行处理

4)可以用websocketsend()方法发送数据给后台,这里只需要获取后台返回的实时数据不需要向后台发送,注释掉了。

三、小程序实现

微信小程序使用wx.connectSocket创建webSocket连接

/**
 * 创建webSocket连接(实时显示车辆信息)
 * @param {String} lineId 线路id
 * @return
 */
createWebSocket: function(lineId) {
    let _this = this;
    let webSocketCode = wx.connectSocket({
        url: rv_request.config.ws + 'business/logistics/internal/stand/webSocket/vehicleStatus/' + lineId,
        method: "GET"
    });

    webSocketCode.onOpen(res => {
        console.info('连接打开成功'); 
    });

    webSocketCode.onError(res => {
        console.info('连接识别');
    });

    webSocketCode.onMessage(res => {
        let data = res.data;
        // todo
    });

    webSocketCode.onClose(() => {
        console.info('连接关闭');
    });
}

1) 在需要的位置this.createWebSocket(),没有参数可以不传

2)url为后台提供给你的地址

3) webSocketCode.onMessage()方法获取返回的数据并进行处理

4) 可以用wx.sendSocketMessage()方法发送数据给后台,具体参考微信小程序api。这里只需要获取后台返回的实时数据不需要向后台发送。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值