UDPSocket 官方文档链接UDPSocket
webSocket 官方文档链接 WebSocket 任务
先用webSocket 测试成功后,由于WSS的问题最后决定用UDPSocket,两个都记录一下。
UDPSocket
项目里主要就使用了以下几个方法, 先用wx.createUDPSocket创建UDP Socket 实例,就能调用里面的方法(前提是都要在小程序后台配置域名,这里不多说)。
onListening 监听开始监听数据包消息的事件,这里不知道可以用在什么地方(欢迎指教),不用也没啥影响 ==
由于只在一个页面上使用,就不封装了,几个关键的变量直接作为全局变量写在js前面。直接代码
// js
var UDPSocket
var portPage({data: {show: false,MCUID:'',recyclingAmount:0,},onLoad(options) {// console.log(options.MCUID)this.setData({MCUID: options.MCUID,})this.createUDPSocket(true) },onShow() {if(!UDPSocket){ this.createUDPSocket(true)}},//创建UDFSocketcreateUDPSocket(isStar){UDPSocket = wx.createUDPSocket()isStar = isStar?isStar:false//首次调用标志isStarif((!UDPSocket) && (!isStar)){wx.showModal({title: 'UDFSocket未创建',content: '重新连接',showCancel: true,complete: (res) => {if(res.confirm){this.createUDPSocket()}}})return}else if(!UDPSocket){return}// UDPSocket 创建后port = UDPSocket.bind(4561) //返回绑定成功的端口号//监听接收数据this.UDPonMessage()//发送心跳this.UDPheartbeat()//10秒发动一次心跳,转一下this,不然会报错heartbeatTimer = setInterval(this.UDPheartbeat.bind(this),10*1000)},//发送UDPsend(data){data = this.formatData(data)UDPSocket.send({address: '消息的地址',port: port,message: data,})},//心跳UDPheartbeat(){console.log("进来心跳")let data = {CommandType:0}this.UDPsend(data)},//监听接收信息UDPonMessage(){UDPSocket.onMessage((e) => {console.log('收到的信息————————',e)// message是收到的信息,类型是ArrayBuffer,要自己转换let message = this.ArrayBufferFunc(e.message)console.log("转换后的信息-------",message)//这里处理自己的逻辑if(message.CommandType == 1){this.setData({show: true,recyclingAmount: 1,})}})},// 开始回收startRecycling(){console.log('点击开始回收',UDPSocket,Boolean(UDPSocket))if(!UDPSocket){this.createUDPSocket()return}let data = {MCUID: this.data.MCUID,CommandType:1 }this.UDPsend(data)},//结束回收closeDialog(){this.setData({show: false,recyclingAmount: 0,})},//关闭连接UDPclose(){if(!UDPSocket){return}clearInterval(heartbeatTimer)UDPSocket.close()UDPSocket = nullheartbeatTimer = null},//处理发送数据formatData(obj){let today = String(new Date().getFullYear()) + (new Date().getMonth()+ 1) + new Date().getDate() let randomNumber = Math.floor(Math.random() * 100000)let RequestID = today + randomNumberobj.RequestID = RequestIDobj.PlayerID = wx.getStorageSync('PlayerID')// console.log(RequestID,obj)let keysArr = Object.keys(obj).sort()let splicingStr = keysArr.reduce((splicingStr,key,index)=>{if(index == 0){splicingStr = key + "=" + obj[key]}else {splicingStr = splicingStr + "&" + key + "=" + obj[key]}return splicingStr},'')splicingStr = splicingStr + "&SecretKey=CD463959-6080-41B3-BE48-A8BB63DE866A"let SignKeyValue = md5.hex_md5(splicingStr)obj.SignKey = SignKeyValue// console.log(keysArr)// console.log(splicingStr)// console.log(obj)console.log("处理后的JSON数据",JSON.stringify(obj))return JSON.stringify(obj)},//ArrayBuffer处理ArrayBufferFunc(buffer){let str = String.fromCharCode.apply(null, new Uint8Array(buffer))return JSON.parse(str)},onHide(){console.log('onHide')this.UDPclose()},onUnload(){console.log('onUnload')this.UDPclose()},/*** 用户点击右上角分享*/onShareAppMessage() {}
})
webSocket
官方推荐用SocketTask 来管理,上代码
// pages/eggRecycle/eggRecycle.js
const md5 = require('../../utils/md5.js')
var SocketTask = null;
//心跳定时器
var heartbeatTimer = null; Page({data: {isTask: false,// 连接是否成功show: false,MCUID:'',recyclingAmount:0,},onLoad(options) {// console.log(options.MCUID)this.setData({MCUID: options.MCUID,})},onShow() {//创建连接this.connectSocket()},//心跳heartbeat(){console.log("进来心跳")let data = {CommandType:0,}this.send(data)heartbeatTimer = setInterval(()=>{this.send(data)},10*1000)},// 创建连接connectSocket() { let isTask= falseSocketTask = wx.connectSocket({url: 'ws://124.222.224.186:8800', //网上的测试地址header: {'content-type': 'application/json'},success: (res => {console.log('创建连接成功', res)fail: (err => {console.log('创建连接失败',err)wx.showModal({title: '创建连接失败'+ err,content: '重新连接',showCancel: false,complete: (res) => {that.connectSocket()}})})})if(ifTask){that.setData({isTask:true,})this.onOpen()this.onMessage()this.onError()this.onClose()}},// 监听 WebSocket 连接打开事件onOpen() {SocketTask.onOpen((res) => {console.log('监听连接打开', res)//心跳this.heartbeat()})},//发送信息send(sendMessage) {let that = thisSocketTask.send({data: this.formatData(sendMessage),success(res) {},fail(err) {}})},// 接收到服务器的消息事件onMessage() {SocketTask.onMessage((data) => {console.log('接受到的服务器信息', data)})},//监听 WebSocket 连接关闭事件onClose() {SocketTask.onClose((data)=>{console.log('监听连接关闭',data)SocketTask = null})},//关闭事件close(){if(!this.data.isTask){return}clearInterval(heartbeatTimer)SocketTask.close()heartbeatTimer = null},// 监听 WebSocket 错误事件onError(){SocketTask.onError((err)=>{console.log('监听 WebSocket 错误事件', err)})},//处理数据formatData(obj){// SecretKey=CD463959-6080-41B3-BE48-A8BB63DE866Alet today = String(new Date().getFullYear()) + (new Date().getMonth()+ 1) + new Date().getDate() let randomNumber = Math.floor(Math.random() * 100000)let RequestID = today + randomNumberobj.RequestID = RequestIDobj.PlayerID = wx.getStorageSync('PlayerID')// console.log(RequestID,obj)let keysArr = Object.keys(obj).sort()let splicingStr = keysArr.reduce((splicingStr,key,index)=>{if(index == 0){splicingStr = key + "=" + obj[key]}else {splicingStr = splicingStr + "&" + key + "=" + obj[key]}return splicingStr},'')splicingStr = splicingStr + "&SecretKey=CD463959-6080-41B3-BE48-A8BB63DE866A"let SignKeyValue = md5.hex_md5(splicingStr)obj.SignKey = SignKeyValue// console.log(keysArr)// console.log(splicingStr)// console.log(obj)console.log("处理后的JSON数据",JSON.stringify(obj))return JSON.stringify(obj)},onHide(){console.log('onHide')this.close()},onUnload(){console.log('onUnload')this.close()},openDialog(){//启动回收let data = {MCUID: this.data.MCUID,CommandType:1 }console.log("发送启动")this.send(data)this.setData({show: true,})},//回收记录getRecord(){wx.navigateTo({url: '../orderRecord/orderRecord?active=3',})},/*** 用户点击右上角分享*/onShareAppMessage() {}
})