前言:以前前端实现实时通信都是用的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。这里只需要获取后台返回的实时数据不需要向后台发送。