websocket封装与使用
创始人
2024-11-14 13:34:03
0

新建WebSocketService.js

export default class WebSocketService {     constructor(url, getSocketMsg, sendSucc) {         this.url = url;         this.getSocketMsg = getSocketMsg;         this.sendSucc = sendSucc; // 发送命令成功后的回调,可有可无 		 		         this.socketTask = null;         this.isOpenSocket = false;         this.socketPrestore = {             state: false,             data: null         };     }      connect() {         this.socketTask = uni.connectSocket({             url: this.url,             success: ()=>{ 				console.log('正在建立socket链接:', this.url); 			},         });          this.socketTask.onOpen(() => { 			console.log("WebSocket连接已发开...!");             this.isOpenSocket = true; 			             if (this.socketPrestore.state) {                 this.sendSocketData(this.socketPrestore.data);                 this.socketPrestore.state = false;             }         });          this.socketTask.onMessage((res)=>{ 			this.getSocketMsg(res) 		});         this.socketTask.onClose(() => {             this.isOpenSocket = false;         });     }; 	sendSocketData(data) { 	    if (this.isOpenSocket) { 	        const sendData = JSON.stringify(data); 			console.log("发送socket数据:", sendData); 	        this.socketTask.send({  				data: sendData, 				success: ()=>{ 					console.log("socket消息发送成功"); 					this.sendSucc && this.sendSucc() 				} 			}); 	    } else { 	        this.socketPrestore.data = data; 	        this.socketPrestore.state = true; 			this.connect(this.url) 	    } 	};     close() {         if (this.isOpenSocket) {             this.socketTask.close();             this.isOpenSocket = false;         }     } } 

关于socketPrestore 部分代码处理机制是根据我的业务添加的,防止发送命令的时候socket链接被服务主动断开做的机制处理,若不需要直接删除就行。

方法调用

 

相关内容

热门资讯

透视资料!德州真人透视脚本(透... 透视资料!德州真人透视脚本(透视)开挂脚本辅助器(哔哩哔哩)1、操作简单,无需德州真人透视脚本手机版...
透视绝活!wepoker软件辅... 透视绝活!wepoker软件辅助程序(透视)开挂脚本软件(哔哩哔哩)1、游戏颠覆性的策略玩法,独创攻...
透视绝活!wepoker养号规... 透视绝活!wepoker养号规律(透视)开挂脚本辅助器(哔哩哔哩)1、操作简单,无需wepoker养...
透视步骤!hh poker透视... 透视步骤!hh poker透视器下载(透视)开挂透视app(哔哩哔哩)1、首先打开hh poker透...
透视演示!we poker辅助... 透视演示!we poker辅助器v3.3(透视)开挂脚本神器(哔哩哔哩)进入游戏-大厅左侧-新手福利...
透视攻略!云扑克有透视吗(透视... 透视攻略!云扑克有透视吗(透视)开挂脚本修改器(哔哩哔哩)1、下载好云扑克有透视吗正确养号方法之后点...
透视学习!aapoker安装包... 透视学习!aapoker安装包怎么使用(透视)开挂脚本下载(哔哩哔哩);1、aapoker安装包怎么...
透视演示!we-poker辅助... 透视演示!we-poker辅助器(透视)开挂脚本辅助器(哔哩哔哩)1.we-poker辅助器 选牌创...
透视总结!德州真人透视脚本(透... 透视总结!德州真人透视脚本(透视)开挂透视辅助器(哔哩哔哩)1、德州真人透视脚本模拟器是什么优化,德...
透视方针!wpk免费辅助(透视... 透视方针!wpk免费辅助(透视)开挂透视工具(哔哩哔哩)1、游戏颠覆性的策略玩法,独创攻略技巧玩法,...