微信小程序websocket连接服务器(接收信息)
app.js
App({ onLaunch: function () { var that = this; // 登录 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId } }) // 获取用户信息 wx.getSetting({ success: res => { if (res.authSetting[scope.userInfo]) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 wx.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId this.globalData.userInfo = res.userInfo // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } } }) } } }) this.initSocket(); }, initSocket() { let that = this this.globalData.SocketTask = wx.connectSocket({ url: wss://*******, }) this.globalData.SocketTask.onOpen(function (res) { console.log(WebSocket连接已打开!readyState= + that.globalData.SocketTask.readyState) var openid = wx.getStorageSync(openid) wx.sendSocketMessage({data:openid}); }) this.globalData.SocketTask.onMessage(function (res) { var objs = JSON.parse(res.data) that.globalData.callback(res) }) this.globalData.SocketTask.onError(function (res) { console.log(readyState= + that.globalData.SocketTask.readyState) that.initSocket() }) this.globalData.SocketTask.onClose(function (res) { console.log(WebSocket连接已关闭!readyState= + that.globalData.SocketTask.readyState) that.initSocket() }) }, globalData: { SocketTask: , callback: function () {}, } })
wxml(接收信息)
app.globalData.callback = function (res) { //res 接收websocket onMessage事件返回的数据 var objs = JSON.parse(res.data) console.log(res) }
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
初学者之如何快速获取微信小程序源码