新建类

class socketIO {
	constructor() {
		this.socketTask = null
		this.is_open_socket = false //避免重复连接
		this.is_show_Loading  = true
		this.url = '连接地址' //连接地址
		this.connectNum = 1 // 重连次数
		this.followFlake = true // traderDetailIndex == true 重连
		//心跳检测
		this.timeout = 15000 //多少秒执行检测
		this.heartbeatInterval = null //
		this.reconnectTimeOut = null //
	}
 
	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
 
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log("正准备建立websocket中...");
				// 返回实例
				return this.socketTask
			},
		});
		
		this.socketTask.onOpen((res) => {
			this.connectNum = 1
			console.log("WebSocket连接正常!");
			
			clearInterval(this.reconnectTimeOut)
			clearInterval(this.heartbeatInterval)
			this.is_open_socket = true;
			this.is_show_Loading = true;
			uni.hideLoading()
			this.start();
			// 注:只有连接正常打开中 ,才能正常收到消息
			this.socketTask.onMessage((e) => {
				// 字符串转json
				let res = JSON.parse(e.data);
				// console.log("res---------->", res) // 这里 查看 推送过来的消息
 
				uni.$emit('getPositonsOrder', res);
 
			});
		})
 
 
 
		// 监听连接失败,这里代码我注释掉的原因是因为如果服务器关闭后,和下面的onclose方法一起发起重连操作,这样会导致重复连接
		uni.onSocketError((res) => {
			console.log('WebSocket连接打开失败,请检查!', this.connectNum);
			
			if(this.is_show_Loading){
				uni.showLoading({
					title: `正在尝试重连`,
					mask: true
				})
			}
			
			
			this.socketTask = null
			this.is_open_socket = false;
			this.is_show_Loading = false;
			clearInterval(this.heartbeatInterval)
			clearInterval(this.reconnectTimeOut)
			// uni.$off('getPositonsOrder')
			// if (this.connectNum < 6000) {
			
			this.reconnect();
			this.connectNum += 1
			// } else {
			// uni.$emit('connectError');
			// this.connectNum = 1
			// }
 
		});
 
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			console.log("已经被关闭了-------")
			clearInterval(this.heartbeatInterval)
			clearInterval(this.reconnectTimeOut)
			this.is_open_socket = false;
			this.is_show_Loading = false;
			this.socketTask = null
			// uni.$off('getPositonsOrder')
			if (this.connectNum < 6) {
				this.reconnect();
			} else {
				uni.$emit('connectError');
				this.connectNum = 1
			}
 
		})
	}
 
 
 
 
	// 主动关闭socket连接
	Close() {
		if (!this.is_open_socket) {
			return
		}
		this.socketTask.close({
			success() {
				uni.showToast({
					title: 'SocketTask 关闭成功',
					icon: "none"
				});
			}
		});
	}
	//发送消息
	send(data) {
		// console.log("data---------->", data);
		// 注:只有连接正常打开中 ,才能正常成功发送消息
		if (this.socketTask) {
			this.socketTask.send({
				data: JSON.stringify(data),
				async success() {
					// console.log("消息发送成功");
				},
			});
		}
	}
 
 
	//开启心跳检测
	start() {
		this.heartbeatInterval = setInterval(() => {
			this.send({
				action: '1003',
				version: '1',
				data: {
					msg: ''
				}
			});
		}, this.timeout)
	}
 
 
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话,进行重连
		if (!this.is_open_socket && this.followFlake) {
			this.reconnectTimeOut = setInterval(() => {
				this.connectSocketInit(this.data);
			}, 3000)
		}
	}
 
}
module.exports = socketIO

main.js导入

import socketIO from '@/util/socket.js'
Vue.prototype.socketIo = new socketIO()

app.vue的 onLaunch 方法加入

this.socketIo.connectSocketInit()

在使用的界面加入

//发送
let sendData = {
	action: '9999',
	version: '1',
	data: {
		    msg: '11111'
	    }
	}
	this.socketIo.send(sendData)
 
 
 
//接受数据
 
uni.$on("getPositonsOrder", (res) => {
				uni.showToast({
					title:JSON.stringify(res),
					icon:'none'
				})
			})