微信小程序websocket
微信小程序带有websocket可以提供使用,但是官方文档写的东西很少,而且小程序后台能力弱这一点也是十分的坑爹,这就导致了socket长连接一切后台就会出现断开的情况,并且难受的是.这个时候你重新调用链接函数也会链接不上,可能直接影响到你的业务逻辑
解决方法就是手动关闭和开启链接,不要让链接在程序切后台的时候被关掉,代码如下↓
- onHide监听程序进入后台的时候,手动关闭链接
onHide: function() {
var that = this;
console.log(‘程序进入了后台‘);
that.closeSocket();
}
- onShow监听程序进入后台的时候,手动开启链接
onShow: function() {
var that = this;
that.connectSocket();
}
- connectSocket函数
/**
* 链接会话,
* 每间隔一秒链接一次,知道链接成功后停止链接
*/
connectSocket() {
var that = this;
var wss_linker = setInterval(function() {
if (that.globalData.user) {
that.globalData.socketTask = wx.connectSocket({
url: that.globalData.socket_url + that.globalData.user.userId,
fail: function(res) {
wx.showModal({
title: ‘提示‘,
content: ‘socket链接异常,请删除程序重试‘,
})
}
})
//监听链接开启
that.globalData.socketTask.onOpen(function(res) {
that.globalData.isConnect = true;
var keep_msg = "keep_connect";
that.globalData.keepConnectInterval = setInterval(function() {
wx.sendSocketMessage({
data: keep_msg,
})
console.log(keep_msg)
if (JSON.stringify(that.globalData.newMsg) == "{}") {
that.globalData.have_new_msg = false;
}
}, 1000)
//获取离线消息
that.get_old_msg(res => {
// 获取在线消息
that.globalData.socketTask.onMessage(function(res) {
var storage_msg = [];
var msg_obj = JSON.parse(res.data);
if (msg_obj.code && msg_obj.code == -1) {
wx.showModal({
title: ‘发送通知‘,
content: msg_obj.msg,
})
// that.globalData.flag=true;
} else {
wx.showToast({
title: ‘You got a msg‘
})
// 处理时间
that.format_date(msg_obj.chatTime, res => {
msg_obj.chatTime = res
var chatRequestUserId = msg_obj.chatRequestUserId + "";
// 把获取的消息存入缓存
that.set_chat_storage(chatRequestUserId, msg_obj);
that.update_unread_msg(chatRequestUserId, msg_obj);
})
}
})
})
console.log(‘webSocket is open‘);
})
that.globalData.socketTask.onClose(function(res){
that.globalData.isConnect = false;
})
clearInterval(wss_linker); //停止计时器
} else {
console.log(‘还没有链接‘)
}
}, 1000)
}
- closeSocket函数
/**
* 关闭socket
*/
closeSocket(){
var that=this;
that.globalData.socketTask.close();
clearInterval(that.globalData.keepConnectInterval);
}
在connectSocket函数中,将建立socket链接返回的socketTask储存在全局变量,用以后续的消息监听、消息发送和socket断开。同时,这里用了全局变量,是为了保持链接一直只有一个。减少程序
错误的情况
ps:这个项目要求在小程序里面做一个聊天的模块=-= 不过也借此熟悉了socket的前后端应用
原文地址:https://www.cnblogs.com/w53064/p/10416578.html
时间: 2024-11-09 02:44:30