這部分比之前的
request
和localStorage
還要難點,不過還是順利移植過來了英融。
因為微信小程序的websocket只允許一條連接,所以復雜情況下還沒進行測試,尚未發(fā)現(xiàn)有什么bug忌傻。
腳本定位
文件:/src/LiveQueryClient.js
函數(shù):_getWebSocketImplementation
代碼:
if (process.env.PARSE_BUILD === 'node') {
return require('ws');
} else if (process.env.PARSE_BUILD === 'browser') {
return typeof WebSocket === 'function' || typeof WebSocket === 'object' ? WebSocket : null;
} else if (process.env.PARSE_BUILD === 'react-native') {
return WebSocket;
}
原理分析
可以看到,在不同的執(zhí)行環(huán)境下搞监,返回不同的WebSocket
對象水孩,但這些都不是微信小程序支持的。
所以我們需要重寫一個簡單的WebSocket
對象
編寫代碼
class WxSocket {
constructor (url) {
wx.connectSocket({
url
});
wx.onSocketOpen((ret) => {
this.onopen && this.onopen(ret);
});
wx.onSocketError(err => {
this.onerror && this.onerror(err);
});
wx.onSocketMessage(msg => {
this.onmessage && this.onmessage(msg);
});
wx.onSocketClose(() => {
this.onclose && this.onclose();
})
}
send (data) {
wx.sendSocketMessage({
data
})
}
close () {
wx.closeSocket();
}
onopen () {}
onerror (error) {}
onclose () {}
onmessage (event) {}
}
然后在上邊的_getWebSocketImplementation
函數(shù)琐驴,直接返回WxSocket
對象即可俘种。