第一步创建一个websocket.js
import variable from './variable.js'//ws长连接...
var connect = function(userId) {
uni.connectSocket({
url: variable.socketUrl + userId
});
uni.onSocketOpen(function(res) {
console.log('WebSocket连接已打开!');
});
uni.onSocketError(function(res) {
console.log('WebSocket连接打开失败,请检查!');
});
uni.onSocketMessage(function (res) {
console.log('收到服务器内容:' + res.data);
//监听推送消息作出对应响应
let noticeType = JSON.parse(res.data).noticeType
if(noticeType == 'message_change'){
uni.$emit('has-new-masg')
}else if(noticeType == 'bd_rescue_alarm'){
uni.$emit('sos-pop-alarm',{
alarms:JSON.parse(res.data).noticeInfo
})
}
});
uni.onSocketClose(function (res) {
console.log('WebSocket 已关闭!');
//监听断开重连
uni.$emit('websocket-close')
});
}
var closeSocket = function(){
uni.closeSocket();
}
module.exports = {
connectSocket:connect,
closeSocket:closeSocket
}
在index.vue中使用
import socket from '@/utils/websocket.js'
onLoad() {
let that = this;
if (that.hasLogin) {
console.log("用户信息-------------", that.userInfo)
// 连接socket
socket.connectSocket(that.userInfo.openid)
uni.$on('websocket-close', res => {
console.log("websoket连接断开重新连接", res)
socket.connectSocket(that.userInfo.openid)
})
}
uni.$on('has-new-masg', res => {
console.log("websoket已经连接推送======消息推送")
})
// sos求救推送
uni.$on('sos-pop-alarm', res => {
console.log("websoket已经连接推送======消息推送", res.alarms)
})
},
简单的socket就可以了