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>
相关推荐
A24207349306 分钟前
微信小程序开发:常用基础语法与指令详解
微信小程序·小程序·notepad++
2501_9159090618 小时前
全面解析iOS应用上架到App Store的完整流程与关键注意事项
android·macos·ios·小程序·uni-app·cocoa·iphone
laboratory agent开发21 小时前
2026小程序系统多维度技术与落地能力深度解析
微信小程序
2501_915106321 天前
iOS 证书类型及作用说明 账号证书与签名配置的完整解读
android·ios·小程序·https·uni-app·iphone·webview
sunywz1 天前
【从零搭建物联网智能充电桩系统】4、Netty WebSocket 服务:小程序实时推送背后的长连接管理
物联网·websocket·小程序
2501_916008892 天前
移动安全之 APP 加固,保障移动应用安全的重要手段
安全·macos·ios·小程序·uni-app·iphone·xcode
2501_915106322 天前
Python爬虫从零开始:七天掌握HTTP协议、数据解析与反爬策略
android·ios·小程序·https·uni-app·iphone·webview
90后的晨仔2 天前
uni-app 项目目录结构全解:每个文件、每个文件夹的作用与配置详解
vue.js·uni-app
爱看老照片2 天前
关于uniapp中单位rpx的注意点
uni-app·rpx
郑州光合科技余经理2 天前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php