どのように小さいプログラムの大域でwebSocketを使いますか?
1913 ワード
どのように小さいプログラムの大域でwebSocketを使いますか?
1)まずap.jsでsocketを初期化し、onLaunch()でinit Socketを呼び出す()
1)まずap.jsでsocketを初期化し、onLaunch()でinit Socketを呼び出す()
// app.js
globalData: {
localSocket: {},
callback: function() {}
},
initSocket() {
let that = this
that.globalData.localSocket = wx.connectSocket({
// url
url: `wss://echo.websocket.org/`
})
// 1.7.0
that.globalData.localSocket.onOpen(function(res) {
console.log('WebSocket !readyState=' + that.globalData.localSocket.readyState)
})
that.globalData.localSocket.onError(function(res) {
console.log('readyState=' + that.globalData.localSocket.readyState)
})
that.globalData.localSocket.onClose(function(res) {
console.log('WebSocket !readyState=' + that.globalData.localSocket.readyState)
that.initSocket()
})
that.globalData.localSocket.onMessage(function(res) {
// websocket
that.globalData.callback(res)
})
},
// ,
sendSocketMessage: function(msg) {
let that = this
return new Promise((resolve, reject) => {
if (this.globalData.localSocket.readyState === 1) {
console.log(' ', msg)
this.globalData.localSocket.send({
data: msg,
success: function(res) {
resolve(res)
},
fail: function(e) {
reject(e)
}
})
} else {
console.log(' ')
}
})
},
2)他のページでsocketメッセージを送信し、pageAなどのsocketメッセージを受け取る. // pageA.js
// socket
sendSocketMessage: function(msg) {
let that = this
return new Promise((resolve, reject) => {
app.sendSocketMessage(msg)
app.globalData.callback = function (res) {
console.log(' ', res)
resolve(res)
}
})
},