如何在⼩程序全局使⽤webSocket 如何在⼩程序全局使⽤ webSocket
1)⾸先在 app.js 中初始化socket, onLaunch() 中调⽤ initSocket()
// app.js
globalData: {
localSocket: {},
callback: function() {}
},
initSocket() {
let that = this
that.globalData.localSocket = wx.connectSocket({
//此处 url 可以⽤来测试
url: `wss:///`
})
//版本库需要在 1.7.0 以上
that.Open(function(res) {
console.log('WebSocket连接已打开!readyState=' + that.adyState)
})
that.Error(function(res) {
console.log('readyState=' + that.adyState)
})
that.Close(function(res) {
console.log('WebSocket连接已关闭!readyState=' + that.adyState)
that.initSocket()
})
that.Message(function(res) {
// ⽤于在其他页⾯监听 websocket 返回的消息
that.globalData.callback(res)
})
},
//统⼀发送消息,可以在其他页⾯调⽤此⽅法发送消息
sendSocketMessage: function(msg) {
let that = this
return new Promise((resolve, reject) => {
if (this.adyState === 1) {
console.log('发送消息', msg)
this.globalData.localSocket.send({websocket和socket
data: msg,
success: function(res) {
resolve(res)
},
fail: function(e) {
reject(e)
}
})
} else {
console.log('已断开')
}
})
},
2)在其他页⾯发送 socket 消息和接受 socket 消息,如在 pageA
// 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)
}
})
},

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。