先在app.js 中声明并初始化以下
startWebSocket: function () {
var that = this;
that.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.然后在新建一个辅助js来发送和接收数据
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)) //这里定义一个onMessage方法,用于每个页面的回调
}) } 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)
}
网友评论