1.這里簡(jiǎn)單的封裝下,先在app.js 中聲明并初始化以下:
startWebSocket: function () {
var that = this;
hat.WebSocketInit()
wx.onSocketError(function () {
})
wx.onSocketMessage(function (data_) {
that.socketOperation(data_)
})
wx.onSocketClose(function (res) {
that.WebSocketInit()
})
},
//連接websocket
WebSocketInit: function () {
wx.connectSocket({
url: this.data.wws,
data: {},
method: 'GET',
success: function (res) {
console.log("connectSocket 成功")
},
fail: function (res) {
console.log("connectSocket 失敗")
}
})
wx.onSocketOpen(function () {
// callback
var mCmd = { "cmd": "connect.Connect", "data": {} }
wx.sendSocketMessage({
data: JSON.stringify(mCmd),
success: function (res) {
console.log("sendSocketMessage 成功")
},
fail: function (res) {
console.log("sendSocketMessage 失敗")
}
})
wx.onSocketMessage(function (data) {
console.log("onSocketMessage ", data)
})
})
},
2.然后在新建一個(gè)輔助js來發(fā)送和接收數(shù)據(jù):
function sendMessage() {
var mCmd = { "cmd": "connect.getWlList", "data": { "mdd": "370600" } }
wx.sendSocketMessage({
data: JSON.stringify(mCmd),
success:function(res){
}
})
}
function resiverMessage(context) {
wx.onSocketMessage(function (data) {
context.onMessage(JSON.parse(data.data)) //這里定義一個(gè)onMessage方法,用于每個(gè)頁(yè)面的回調(diào)
}) } module.exports = { formatNumber: formatNumber, judge: judge, sendMessage: sendMessage, resiverMessage: resiverMessage }
3.開始使用:
onMessage: function (res) {
this.setData({ data: res.data });
console.log(res);
},
onLoad: function (options) {
app.data.util.sendMessage();
app.data.util.resiverMessage(this)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。