uni-app vue3封装websocket,支持微信小程序

一、创建useWebSocket.js 文件

javascript 复制代码
// useWebSocket.js 

// 获取链接的URL前缀
import {
	BASE_URL
} from "./request";
 
import {
	ref,
	onMounted,
	onBeforeUnmount
} from "vue";

// 假设我们使用 uni-app 的 globalData 或 Vuex 来管理用户状态  
// 这里为了简单起见,我们假设用户ID是直接从某处获取的  

const useWebSocket = (
	url,
	reconnectInterval = 10000,
	maxReconnectAttempts = 5
) => {
	const isMounted = ref(true);
	const isConnected = ref(false);
	const messages = ref([]);
	let reconnectAttempts = 0;

	const connect = () => {
		if (isConnected.value) {
			uni.closeSocket(); // 关闭已有的 WebSocket 连接  
		}

		const uri = `ws://${BASE_URL}/websocket/tender/${url}`;

		// 使用微信小程序的 WebSocket API  
		uni.connectSocket({
			url: uri,
			success: () => {
				console.log("WebSocket连接已打开");
				isConnected.value = true;
				// 监听消息  
				uni.onSocketMessage((res) => {
					messages.value = JSON.parse(res.data);
				});

				// 监听WebSocket的关闭  
				uni.onSocketClose(() => {
					console.log("WebSocket连接已关闭");
					isConnected.value = false;
					if (isMounted.value && reconnectAttempts < maxReconnectAttempts) {
						setTimeout(connect, reconnectInterval * (reconnectAttempts + 1));
						reconnectAttempts++;
					}
				});

				// 监听WebSocket的错误  
				uni.onSocketError((res) => {
					console.error("WebSocket发生错误:", res.errMsg);
					if (isMounted.value) {
						setTimeout(connect, reconnectInterval);
					}
				});
			},
			fail: (err) => {
				console.error("WebSocket连接失败:", err);
			}
		});
	};

	const sendMessage = (message) => {
		if (isConnected.value) {
			uni.sendSocketMessage({
				data: message,
				success: () => {
					console.log('消息发送成功');
				},
				fail: (err) => {
					console.error('发送失败', err);
				}
			});
		}
	};

	onMounted(() => {
		isMounted.value = true;
		connect();
	});

	onBeforeUnmount(() => {
		isMounted.value = false;
		if (isConnected.value) {
			uni.closeSocket();
		}
	});

	return {
		isConnected,
		messages,
		sendMessage
	};
};

export default useWebSocket;

二、在 .vue文件中使用

javascript 复制代码
<script setup>

import {
		onLoad
	} from "@dcloudio/uni-app";

	import {
		ref,
		watchEffect
	} from 'vue';
// 引入useWebSocket
import useWebSocket from "@/api/useWebSocket.js";
onLoad((options) => {
		id.value = options.id
		messages.value = useWebSocket(options.id, 10000, 5);
	})

// 监听messages
watchEffect(() => {
		let timeVal = {
			...messages.value
		};
		console.log(timeVal);
	})

</script>
相关推荐
2501_9339072120 小时前
宁波小程序开发服务与技术团队专业支持
科技·微信小程序·小程序
带娃的IT创业者1 天前
工具状态失踪之谜:EventBus事件漏接与asyncio.Lock并发陷阱双线诊断
qt·websocket·并发控制·eventbus·事件驱动架构·pwa·asyncio.lock
sheji34161 天前
【开题答辩全过程】以 基于微信小程序的少儿编程学习平台为例,包含答辩的问题和答案
学习·微信小程序·小程序
const_qiu1 天前
微信小程序自动化测试100%通过率实践
微信小程序·小程序
特立独行的猫a1 天前
ESP32小智AI的WebSocket 调试工具实现,小智AI后台交互过程揭秘(一、开篇介绍 )
人工智能·websocket·网络协议·esp32·小智ai
特立独行的猫a1 天前
ESP32小智AI的WebSocket 调试工具的实现,小智AI后台交互过程揭秘(二、技术原理与实现过程详解 )
人工智能·websocket·网络协议·esp32·调试工具·小智ai
你的眼睛會笑1 天前
uni-app 实战:使用 lime-painter 实现页面内容一键生成海报并下载
uni-app
一字白首1 天前
微信小程序进阶实战:从 UI 组件库到全局状态管理全解DAY05
ui·微信小程序·小程序
一只程序熊1 天前
uniapp 高德地图 打开选择地址报错,也没有展示出附近的位置
android·uni-app
带娃的IT创业者2 天前
WeClaw 日志分析实战:如何从海量日志中快速定位根因?
运维·python·websocket·jenkins·fastapi·架构设计·实时通信