WebSocket 是HTML5中提供的新特性,可以用来在需要及时、双向通讯的场景。比如聊天,消息推送等。 微信小程序对 WebSocket提供了支持。
微信小程序API为使用 WebSocket 提供了一组API, 包括 connectSocket, sendSocketMessage 等,下面我们通过一个简单的示例来演示:
因为WebSocekt是一个双向的长连接,所以我们通常在一个应用中使用一个连接即可,所以在示例中我们将WeScoket定义为全局变量,在 app.js 的globalData中加一个新的变量定义:
1 2 3
| globalData: { wsSocket: null }
|
然后将 index.wxml 文件改为:
1 2 3 4 5 6
| <view> <button bindtap='onStart'>{{btnTitle}}</button> </view> <view> <text>{{message}}</text> </view>
|
对应的 index.js 文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| const app = getApp()
Page({ data: { message: '', isOpen: false, btnTitle: '开启监听' },
onLoad: function() {
},
onStart: function() {
if (!this.data.isOpen) { app.globalData.wsSocket = wx.connectSocket({ url: 'ws://uat.hohistar.com.cn:8080/websocket/3123', success: function(res) { console.log('success: ' + JSON.stringify(res)) }, fail: function(e) { console.log('fail: ' + e) }, complete: function(res) { console.log('complete: ' + JSON.stringify(res)) } })
app.globalData.wsSocket.onOpen((res) => { console.log('wsSocket, onOpen, ' + JSON.stringify(res)) })
app.globalData.wsSocket.onClose(res => { console.log('wsSocket, onClose, ' + JSON.stringify(res)) })
app.globalData.wsSocket.onError(e => { console.log('wsSocket, onError: ' + e) })
app.globalData.wsSocket.onMessage(res => { console.log('wsSocket, onMessage: ' + JSON.stringify(res)) this.setData({ message: this.data.message + res.data + '\n' }) }) this.setData({ isOpen:true, btnTitle: '关闭监听' }) } else { app.globalData.wsSocket.close() this.setData({ isOpen: false, btnTitle: '开启监听' }) }
}
})
|