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>
相关推荐
oooo_z2 小时前
WebSocket实时行情推送API实战:用iTick搭一个盯盘小工具
网络·websocket·网络协议
PHP实战开发录4 小时前
微信小程序多环境配置混用排查记录
微信小程序·php·开发·接口隔离原则
【赫兹威客】浩哥21 小时前
基于SpringBoot+Vue3的健身运动管理系统|WebSocket实时消息 健身房毕设项目
spring boot·websocket·课程设计
qq_316837751 天前
uniapp + Vite + ffmpeg-wasm 0.12.x 集成示例
ffmpeg·uni-app·wasm
zhangminghuan1 天前
微信小程序开发核心知识点全景解析(前端必备硬核基础)
前端·微信小程序·小程序
游戏开发爱好者81 天前
开心上架是什么,一站式 Apple 开发者工作台总览
android·小程序·https·uni-app·iphone·webview
年年CODE1 天前
uni-app 实现 AI 流式问答:H5 EventSource 与微信小程序 onChunkReceived 的兼容方案
uni-app
sltin1 天前
需求到落地:我如何在微信小程序里实现证件照换底、隐私打码与水印相机
数码相机·微信小程序·小程序
lhldsg1 天前
从匿名倾诉到树洞社交:基于Spring Boot与uniapp的多端匿名社交系统设计与实现
spring boot·后端·uni-app