| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165 |
- // utils/websocket.js
- class LocalWebSocket {
- constructor() {
- this.socket = null;
- this.isConnected = false;
- this.reconnectTimer = null;
- this.reconnectCount = 0;
- this.maxReconnectAttempts = 5;
- this.reconnectDelay = 3000;
-
- // 默认配置
- this.defaultConfig = {
- ip: '192.168.1.100',
- port: 8080,
- path: '/websocket'
- };
-
- this.storageKey = 'WEBSOCKET_SERVER_CONFIG';
- }
- // 从本地存储获取配置
- getConfig() {
- try {
- const configStr = uni.getStorageSync(this.storageKey);
- if (configStr) {
- return JSON.parse(configStr);
- }
- return this.defaultConfig;
- } catch (error) {
- console.error('获取WebSocket配置失败:', error);
- return this.defaultConfig;
- }
- }
- // 保存配置到本地存储
- saveConfig(config) {
- try {
- uni.setStorageSync(this.storageKey, JSON.stringify(config));
- return true;
- } catch (error) {
- console.error('保存WebSocket配置失败:', error);
- return false;
- }
- }
- // 获取WebSocket连接URL
- getWebSocketURL() {
- const config = this.getConfig();
- return `ws://${config.ip}:${config.port}${config.path}`;
- }
- // 连接WebSocket
- connect() {
- if (this.socket && this.isConnected) {
- console.log('WebSocket已连接');
- return;
- }
- const url = this.getWebSocketURL();
- console.log('尝试连接WebSocket:', url);
- // 创建WebSocket连接
- this.socket = new WebSocket(url);
- // 监听连接成功
- this.socket.onopen = (event) => {
- console.log('WebSocket连接成功');
- this.isConnected = true;
- this.reconnectCount = 0;
- this.onOpen && this.onOpen(event);
- };
- // 监听消息接收
- this.socket.onmessage = (event) => {
- console.log('收到WebSocket消息:', event.data);
- this.onMessage && this.onMessage(event);
- };
- // 监听连接关闭
- this.socket.onclose = (event) => {
- console.log('WebSocket连接关闭:', event);
- this.isConnected = false;
- this.onClose && this.onClose(event);
- this.handleReconnect();
- };
- // 监听错误
- this.socket.onerror = (error) => {
- console.error('WebSocket连接错误:', error);
- this.onError && this.onError(error);
- };
- }
- // 处理重连
- handleReconnect() {
- if (this.reconnectCount < this.maxReconnectAttempts) {
- this.reconnectCount++;
- console.log(`WebSocket尝试重连 (${this.reconnectCount}/${this.maxReconnectAttempts})`);
-
- this.reconnectTimer = setTimeout(() => {
- this.connect();
- }, this.reconnectDelay * this.reconnectCount);
- } else {
- console.log('WebSocket重连次数已达上限');
- }
- }
- // 发送消息
- send(data) {
- if (this.isConnected && this.socket) {
- if (typeof data === 'object') {
- data = JSON.stringify(data);
- }
- this.socket.send(data);
- return true;
- } else {
- console.warn('WebSocket未连接,无法发送消息');
- return false;
- }
- }
- // 关闭连接
- close() {
- if (this.socket) {
- this.socket.close();
- this.socket = null;
- }
- if (this.reconnectTimer) {
- clearTimeout(this.reconnectTimer);
- this.reconnectTimer = null;
- }
- this.isConnected = false;
- }
- // 更新服务端配置
- updateServerConfig(newConfig) {
- const config = { ...this.defaultConfig, ...newConfig };
- this.saveConfig(config);
-
- // 如果当前已连接,重新连接
- if (this.isConnected) {
- this.close();
- this.connect();
- }
- }
- // 设置回调函数
- setOnOpen(callback) {
- this.onOpen = callback;
- }
- setOnMessage(callback) {
- this.onMessage = callback;
- }
- setOnClose(callback) {
- this.onClose = callback;
- }
- setOnError(callback) {
- this.onError = callback;
- }
- }
- export default new LocalWebSocket();
|