使用uni-app开发微信小程序,使用了WebSocket + Stomp发送数据。
但是在iPhone不能正常工作,在微信开发工具和安卓手机都没问题。
试了很多种方法,最后找到了解决方案。
// ios 缺少 0x00 导致解析失败
let socketOpen = false
let socketMsgQueue = []
export default {
client: null,
baseURL: 'ws://localhost:8080/stomp',
init() {
if (this.client) {
console.log('use connected client')
return Promise.resolve(this.client)
}
return new Promise((resolve, reject) => {
const ws = {
send: this.sendMessage,
onopen: null,
onmessage: null,
close: this.closeSocket,
}
uni.connectSocket({
url: this.baseURL,
header: {
'X-ACCESS-TOKEN': uni.getStorageSync('token'),
},
})
uni.onSocketOpen(res => {
console.log('WebSocket连接已打开!', res)
socketOpen = true
for (let i = 0; i < socketMsgQueue.length; i++) {
ws.send(socketMsgQueue[i])
}
socketMsgQueue = []
ws.onopen && ws.onopen()
})
uni.onSocketMessage(res => {
if (res && res.data) {
let value = res.data
let code = value.charCodeAt(value.length - 1)
// ios 缺少 0x00 导致解析失败
if (code !== 0x00) {
value += String.fromCharCode(0x00)
res.data = value
}
}
ws.onmessage && ws.onmessage(res)
})
uni.onSocketError(res => {
console.log('WebSocket 错误!', res)
reject(res)
})
uni.onSocketClose((res) => {
this.client.disconnect()
this.client = null
socketOpen = false
console.log('WebSocket 已关闭!', res)
reject(res)
})
const Stomp = require('./stomp.js').Stomp
const client = this.client = Stomp.over(ws)
client.reconnect_delay = 3000
client.connect({}, () => {
console.log('stomp connect')
resolve(client)
}, (error) => {
console.error(error)
})
})
},
disconnect(reason = '') {
console.log('disconnect', reason)
uni.closeSocket({reason: reason})
},
sendMessage(message) {
if (socketOpen) {
uni.sendSocketMessage({
data: message,
})
} else {
socketMsgQueue.push(message)
}
},
closeSocket() {
console.log('closeSocket')
},
}
https://raw.githubusercontent.com/stomp-js/stomp-websocket/master/lib/stomp.js