var socketOpen = false;
var count = 0;
var SocketTask;
var url = 'xxxx';
Page({
data: {
},
onLoad: function (options) {
},
onReady: function () {
var that = this;
SocketTask.onOpen(res => {
socketOpen = true;
console.log('监听 WebSocket 连接打开事件。', res)
})
SocketTask.onClose(onClose => {
console.log('监听 WebSocket 连接关闭事件。', onClose)
socketOpen = false;
that.webSocket()
})
SocketTask.onError(onError => {
console.log('监听 WebSocket 错误。错误信息', onError)
socketOpen = false
})
SocketTask.onMessage(res => {
console.log('监听 WebSocket 连接打开事件。', res)
})
},
onShow: function () {
var that = this;
that.initAnimation();
wx.startAccelerometer({
interval: 'ui'
});
wx.onAccelerometerChange(function (e) {
if (e.x > .7 && e.y > .7) {
++count;
if(count%2==0){
setTimeout(function () {
that.shake();
}, 400);
that.sendSocketMessage();
console.log(count);
}
}
});
if (!socketOpen) {
that.webSocket()
}
},
onHide: function () {
SocketTask.close(function (close) {
console.log('关闭 WebSocket 连接。', close)
})
wx.stopAccelerometer();
},
onUnload: function () {
wx.stopAccelerometer();
},
initAnimation:function(){
var that = this;
that.animation = wx.createAnimation({
duration: 100,
timingFunction: "ease",
delay: 0,
transformOrigin: 'center bottom',
success: function (res) {
console.log(res)
}
});
},
shake:function(){
var that = this;
wx.vibrateLong();
that.animation
.translate(25).rotate(20).step()
.translate(0).step()
.translate(-25).rotate(-20).step()
.translate(5).rotate(5).step()
.translate(0).step()
.translate(-5).rotate(-5).step()
.translate(0).rotate(0).step();
that.setData({
animation: that.animation.export()
});
},
webSocket:function () {
SocketTask = wx.connectSocket({
url: url,
data: 'data',
header: {
'content-type': 'application/json'
},
method: 'post',
success: function (res) {
console.log('WebSocket连接创建', res)
},
fail: function (err) {
wx.showToast({
title: '网络异常!',
})
console.log(err)
},
})
},
sendSocketMessage:function() {
var that = this;
var message = {
"user_id": userid,
"user_name": username,
"user_avatar": useravatar,
"user_phone": userphone
}
console.log('通过 WebSocket 连接发送数据', JSON.stringify(message))
SocketTask.send({
data: JSON.stringify(message)
}, function (res) {
console.log('已发送', res)
})
},
})
<view class="shake_ani" animation="{{animation}}">
<image src="摇一摇的图片"></image>
</view>