一、新建websocket.js文件

在common目录下新建一个websocket.js文件,完整代码如下

class websocketUtil {
	constructor(url, time) {
		this.is_open_socket = false //是否在连接中
		this.url = url //websocket地址
		this.data = null
		//心跳检测
		this.intervalTime = time //多少秒执行检测
		this.heartbeatInterval = null //检测服务器端是否还活着
		this.reconnectInterval = null //重连之后多久再次重连
		try {
			return this.connectSocketInit()
		} catch (e) {
			this.is_open_socket = false
			// this.reconnect();
		}
	}

	// 创建websocket连接
	connectSocketInit() {
		if(this.is_open_socket==true){
			return
		}
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				this.is_open_socket = true;
				// console.log("正准备建立websocket中...");
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			// console.log("WebSocket连接正常!");
			clearInterval(this.reconnectInterval)
			clearInterval(this.heartbeatInterval)
			this.is_open_socket = true;
			this.start();
			// 注:只有连接正常打开中 ,才能正常收到消息
			this.socketTask.onMessage((res) => {
				console.log(res.data)
			});
		})
		// 监听连接失败
		uni.onSocketError((res) => {
			// console.log('WebSocket连接打开失败,请检查!', JSON.stringify(res));
			this.is_open_socket = false;
			if (this.socketTask) {
				this.socketTask.close()
			}
			// this.reconnect();
		});
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			// console.log("已经被关闭了")
			this.is_open_socket = false;
			// this.reconnect();
		})
	}

	//发送消息
	async send(value) {
		await new Promise((resolve) => {
			setTimeout(() => {
				resolve();
			}, 1000);
		});
		this.socketTask.send({
			data: 'connected:' + uni.getStorageSync('userinfo').user_id,
			async success() {
				// console.log("消息发送成功", value);
			},
		});
	}
	//关闭连接
	close() {
		this.socketTask.close()
	}

	//开启心跳检测
	start() {
		let that = this
		this.heartbeatInterval = setInterval(() => {
			that.data = 'connected:' + uni.getStorageSync('userinfo').user_id
			that.send(that.data);
		}, this.intervalTime)
	}
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话,进行重连
		if (!this.is_open_socket) {
			this.reconnectInterval = setInterval(() => {
				this.connectSocketInit();
			}, 3000)
		}
	}
	//外部获取消息
	getMessage(callback) {
		this.socketTask.onMessage((res) => {
			return callback(res)
		})
		uni.onSocketClose((res) => {
			this.is_open_socket = false;
			return callback('close')
		});
		uni.onSocketError((res) => {
			this.is_open_socket = false;
			return callback('error')
		});
	}
}

module.exports = websocketUtil

二、调用方式

1.全局调用

挂载到全局

//main.js
import wsRequest from "@/common/websocket.js"

// 开启websocket
let websocket = new wsRequest("ws://xxx.xx.xxx.xxx:xxxx",5000)
//挂载到全局
Vue.prototype.$socket = websocket

在页面中调用

// 发送消息
let data = "发送的消息"
this.$socket.send(data);
// 接收消息
this.$socket.getMessage(res => {
	console.log("接收消息:",res)
})

2.单页面调用

<script>
	import wsRequest from "@/common/websocket.js"
	export default {
		data() {
			return {
				socket: null,
			}
		},
		mounted() {
			this.socket = new wsRequest('你的url',5000);
			let data = '传递的消息';
			this.socket.send(data);
			this.watchSocket();
		},
		methods: {
			watchSocket() {
				this.socket.getMessage(res=> {
					console.log("消息接收:", res);
				})
			},
		}
	}
</script>

转载于:uni-app使用websocket(封装、心跳检测)_uniapp websocket-CSDN博客

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐