小程序与服务器通信webSocket和UDPSocket
UDPSocket 官方文档链接UDPSocket
webSocket 官方文档链接 WebSocket 任务
先用webSocket 测试成功后,由于WSS的问题最后决定用UDPSocket,两个都记录一下。
UDPSocket
项目里主要就使用了以下几个方法, 先用wx.createUDPSocket创建UDP Socket 实例,就能调用里面的方法(前提是都要在小程序后台配置域名,这里不说)。
onListening 监听开始监听数据包消息的事件,这里不知道有在什么地方(欢迎指教),不用也没啥影响 ==
由于只在一个页面上使用,就不封装了,几个关键的变量直接作为全局变量写在js前面。直接代码
// js
var UDPSocket
var port
Page({
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)}
},
//创建UDFSocket
createUDPSocket(isStar){
UDPSocket = wx.createUDPSocket()
isStar = isStar?isStar:false
//首次调用标志isStar
if((!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秒发动一次心跳
heartbeatTimer = setInterval(this.UDPheartbeat,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 = null
heartbeatTimer = 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 + randomNumber
obj.RequestID = RequestID
obj.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= false
SocketTask = 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 = this
SocketTask.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-A8BB63DE866A
let today = String(new Date().getFullYear()) + (new Date().getMonth()+ 1) + new Date().getDate()
let randomNumber = Math.floor(Math.random() * 100000)
let RequestID = today + randomNumber
obj.RequestID = RequestID
obj.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() {
}
})