// utils/ipDiscovery.js class IPDiscovery { constructor() { this.commonIPs = [ '192.168.1.100', '192.168.0.100', '10.0.0.100', '127.0.0.1' ]; this.defaultPort = 8080; this.defaultPath = '/websocket'; } // 检测指定IP的WebSocket服务是否可用 async checkWebSocketServer(ip, port = this.defaultPort) { return new Promise((resolve) => { const url = `ws://${ip}:${port}${this.defaultPath}`; let socket = new WebSocket(url); let timeoutTimer = null; const cleanup = () => { if (socket) { socket.close(); socket = null; } if (timeoutTimer) { clearTimeout(timeoutTimer); } }; timeoutTimer = setTimeout(() => { cleanup(); resolve(false); }, 3000); socket.onopen = () => { cleanup(); resolve(true); }; socket.onerror = () => { cleanup(); resolve(false); }; }); } // 自动发现可用的WebSocket服务端 async autoDiscoverServer() { console.log('开始自动发现WebSocket服务端...'); for (let ip of this.commonIPs) { console.log(`检测 ${ip}:${this.defaultPort}...`); const isAvailable = await this.checkWebSocketServer(ip, this.defaultPort); if (isAvailable) { console.log(`找到可用的WebSocket服务端: ${ip}:${this.defaultPort}`); return { ip: ip, port: this.defaultPort, path: this.defaultPath }; } } console.log('未找到可用的WebSocket服务端,使用默认配置'); return { ip: this.commonIPs[0], port: this.defaultPort, path: this.defaultPath }; } // 获取本机网络信息(尝试获取) async getLocalNetworkInfo() { return new Promise((resolve) => { // 获取网络类型 uni.getNetworkType({ success: (res) => { console.log('网络类型:', res.networkType); } }); // 获取WiFi信息(部分平台支持) // 注意:这个API可能需要特定权限 if (uni.getConnectedWifi) { uni.getConnectedWifi({ success: (res) => { console.log('WiFi信息:', res.wifi); }, fail: (err) => { console.log('获取WiFi信息失败:', err); } }); } // 返回默认的本地IP段 resolve({ localIPRange: '192.168.1.x' }); }); } } export default new IPDiscovery();