您的位置:首页 > 健康 > 养生 > seo收费低_管理咨询公司名称_seo全称是什么_最近五天的新闻大事

seo收费低_管理咨询公司名称_seo全称是什么_最近五天的新闻大事

2024/10/6 18:20:39 来源:https://blog.csdn.net/weixin_45483535/article/details/142517844  浏览:    关键词:seo收费低_管理咨询公司名称_seo全称是什么_最近五天的新闻大事
seo收费低_管理咨询公司名称_seo全称是什么_最近五天的新闻大事

小程序websocket最佳实践,有心跳和断线重连

封装了WebSocketHandler类,用于管理websocket链接,保证链接的稳定和可靠,该类主要适用于小程序,但其设计思想和方法也适用于其他平台。

export default class WebSocketHandler {constructor() {// 获取环境变量this.env = wx.getStorageSync('env');// 生产环境的 WebSocket 地址this.prod = 'www.xx.com';// 开发环境的 WebSocket 地址this.dev = 'www.xx.com';// 根据环境变量选择 WebSocket 地址this.path = `${(this.env == 'pro' || !this.env) ? this.prod : this.dev}`;// 构建 WebSocket URLthis.url = `wss://${this.path}/websocket`;// 重连次数限制this.limit = 0;// WebSocket 连接状态标志this.isClose = true;// 存储未发送的消息this.preParams = '';// 重连锁this.lockReconnect = false;// 重连定时器this.timer = null;// 心跳检测机制this.heartCheck = {timeout: 3000, // 心跳检测间隔timeoutObj: null, // 客户端定时器serverTimeoutObj: null, // 服务端定时器reset: function () {// 重置定时器clearTimeout(this.timeoutObj);clearTimeout(this.serverTimeoutObj);return this;},start: () => {// 启动心跳检测this.heartCheck.timeoutObj = setTimeout(() => {// 发送 PING 消息wx.sendSocketMessage({data: "PING",success() {// 发送成功}});// 设置服务端定时器,如果超时则关闭连接this.heartCheck.serverTimeoutObj = setTimeout(() => {wx.closeSocket();}, this.heartCheck.timeout);}, this.heartCheck.timeout);}};// 绑定 WebSocket 事件处理函数this._onSocketOpen();this._onSocketMessage();this._onSocketError();this._onSocketClose();}/*** 创建 WebSocket 连接* @param {Object} options - 建立连接时需要的配置信息* @param {string} options.userId - 用户 ID* @param {string} options.agentId - 代理 ID*/connect({ userId}) {if (!this.isClose) {logger.info('WebSocket is already connected or connecting.');return;}wx.connectSocket({url: `${this.url}/${userId}`,header: {'content-type': 'application/json'},method: 'POST'});}/*** 发送消息* @param {Object} params - 要发送的消息参数* @returns {Promise} - 返回一个 Promise,表示消息发送的结果*/send(params) {return new Promise((resolve, reject) => {const cruParams = JSON.stringify(params);if (this.isClose) {this.preParams = params;return;}logger.debug(`send---`, JSON.stringify(cruParams));wx.sendSocketMessage({data: cruParams,success: (res) => {logger.debug('sendSocketMessage', JSON.stringify(res));resolve({ res });},fail: (res) => {logger.error('sendSocketMessage', JSON.stringify(res));reject(res);},});});}/*** 关闭 WebSocket 连接*/closeConnection() {this.isClose = true;wx.closeSocket();}/*** 处理 WebSocket 错误事件*/_onSocketError() {wx.onSocketError((res) => {this.isClose = true;logger.error('WebSocket连接打开失败,请检查!', JSON.stringify(res));this.reconnect();});}/*** 处理 WebSocket 关闭事件*/_onSocketClose() {wx.onSocketClose((res) => {this.isClose = true;logger.error('WebSocket 已关闭!', JSON.stringify(res));this.reconnect();});}/*** 处理 WebSocket 打开事件*/_onSocketOpen() {wx.onSocketOpen(() => {logger.debug('WebSocket连接已打开!');this.heartCheck.reset().start();if (this.isClose && this.preParams) {logger.info('重新发送WebSocket消息!');wx.sendSocketMessage({data: JSON.stringify(this.preParams),success: () => {logger.debug('重新发送--sendSocketMessage', JSON.stringify(this.preParams));this.preParams = '';},fail: (res) => {logger.error('重新发送--sendSocketMessage-fail', JSON.stringify(res));},});} else {wx.sendSocketMessage({data: "PING",});}this.isClose = false;});}/*** 处理 WebSocket 消息事件*/_onSocketMessage() {wx.onSocketMessage((res) => {if (res.data == "PONG") {console.log('PONG成功');this.heartCheck.reset().start();}});}/*** 尝试重新连接 WebSocket*/reconnect() {if (this.lockReconnect) return;this.lockReconnect = true;clearTimeout(this.timer);if (this.limit < 50) {this.timer = setTimeout(() => {this.lockReconnect = false;}, 300);this.limit = this.limit + 1;}}
}
// 使用时
this.wsHandler = new WebSocketHandler();
app.wsHandler.send(params).then();

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com