| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- // utils/WebSocketManager.js
- import LocalWebSocket from './websocket.js';
- import IPDiscovery from './ipDiscovery.js';
- class WebSocketManager {
- constructor() {
- this.ws = LocalWebSocket;
- this.ipDiscovery = IPDiscovery;
- this.isAutoDiscovering = false;
- }
- // 初始化WebSocket连接
- async init() {
- // 首先尝试自动发现服务端
- await this.autoDiscoverAndConnect();
-
- // 设置默认回调
- this.setupDefaultCallbacks();
- }
- // 自动发现并连接
- async autoDiscoverAndConnect() {
- if (this.isAutoDiscovering) return;
-
- this.isAutoDiscovering = true;
-
- try {
- // 先尝试使用已保存的配置
- const savedConfig = this.ws.getConfig();
- const isAvailable = await this.ipDiscovery.checkWebSocketServer(
- savedConfig.ip,
- savedConfig.port
- );
-
- if (isAvailable) {
- console.log('使用已保存的配置连接WebSocket');
- this.ws.connect();
- } else {
- console.log('已保存的配置不可用,开始自动发现...');
- const discoveredConfig = await this.ipDiscovery.autoDiscoverServer();
- this.ws.updateServerConfig(discoveredConfig);
- this.ws.connect();
- }
- } catch (error) {
- console.error('自动发现服务端失败:', error);
- // 使用默认配置连接
- this.ws.connect();
- } finally {
- this.isAutoDiscovering = false;
- }
- }
- // 设置默认回调
- setupDefaultCallbacks() {
- this.ws.setOnOpen((event) => {
- console.log('WebSocket已连接');
- uni.$emit('websocket-connected');
- });
- this.ws.setOnMessage((event) => {
- try {
- const data = JSON.parse(event.data);
- // 通过事件总线发送消息
- uni.$emit('websocket-message', data);
- } catch (error) {
- console.error('解析WebSocket消息失败:', error);
- }
- });
- this.ws.setOnClose((event) => {
- console.log('WebSocket已断开');
- uni.$emit('websocket-disconnected');
- });
- this.ws.setOnError((error) => {
- console.error('WebSocket错误:', error);
- uni.$emit('websocket-error', error);
- });
- }
- // 发送消息
- sendMessage(data) {
- return this.ws.send(data);
- }
- // 更新服务端配置
- async updateServerConfig(config) {
- this.ws.updateServerConfig(config);
- // 重新连接
- this.ws.close();
- this.ws.connect();
- }
- // 获取当前配置
- getCurrentConfig() {
- return this.ws.getConfig();
- }
- // 手动连接
- connect() {
- this.ws.connect();
- }
- // 断开连接
- disconnect() {
- this.ws.close();
- }
- // 重新连接
- reconnect() {
- this.ws.close();
- this.ws.connect();
- }
- }
- export default new WebSocketManager();
|