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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| Page({
data: { _height: '', msg: '', countNum: 0, msgArr: [], websocketId: '' }, sendMsg(){ console.log(wx.getStorageSync('userInfo').nickName); let msg = { "websocketId": this.data.websocketId, "status": "send", "nickname": wx.getStorageSync('userInfo').nickName, "msg": this.data.msg } wx.sendSocketMessage({ data: JSON.stringify(msg) }) this.setData({ msg: '' }) }, onChatInfoChange(e){ console.log(e.detail.value); this.setData({ msg: e.detail.value }) }, scrollHeight(){ let _this = this; wx.getSystemInfo({ success: function(res) { let windowHeight = res.windowHeight; _this.setData({ _height: (windowHeight - 61) + 'px' }) } }) }, connectWebsocket() { let _this = this; let loginUserInfo = { 'websocketId': this.data.websocketId, 'status': 'login' } wx.connectSocket({ url: 'ws://192.168.1.108:3001' }) wx.onSocketOpen(function (re) { console.log('WebSocket连接已打开!'); wx.sendSocketMessage({ data: JSON.stringify(loginUserInfo) }) wx.onSocketMessage(function (result) { console.log('收到服务器内容:' + result.data); let res = JSON.parse(result.data), msgArr = _this.data.msgArr; console.log(res) if (res.rstMsg.msg){ msgArr.push(res.rstMsg); _this.setData({ msgArr: msgArr }) } else{ _this.setData({ countNum: res.rstMsg.count }) } }) }) },
onLoad: function (options) { this.scrollHeight(); this.setData({ websocketId: 'user_'+ wx.getStorageSync('openId') }) this.connectWebsocket(); wx.onSocketError(function (res) { console.log('WebSocket由于错误已关闭!'); }) wx.onSocketClose(function (res) { console.log('WebSocket 已关闭!'); }) },
onUnload: function () { wx.closeSocket(); } })
|