'use strict'; const { Controller } = require('ee-core'); const Log = require('ee-core/log'); const CoreWindow = require('ee-core/electron/window'); const WebSocket = require('ws'); // 引入原生 ws 库 class SocketController extends Controller { constructor(ctx) { super(ctx); this.socket = null; } /** * Connect to WebSocket server */ connect() { this.socket = new WebSocket('ws://10.56.42.176:7074/ws'); // 监听连接成功事件 this.socket.on('open', () => { Log.info('Connected to WebSocket server'); this.sendPing(); // 连接成功后发送 ping }); // 监听消息事件 this.socket.on('message', (data) => { Log.info('Received:', data.toString()); }); // 监听连接关闭事件 this.socket.on('close', () => { Log.info('Disconnected from WebSocket server'); }); // 监听错误事件 this.socket.on('error', (err) => { Log.error('WebSocketError:', err); }); setInterval(()=>{ const win = CoreWindow.getMainWindow(); win.webContents.send('controller.socket.message', '这是一个消息'); },2000) } /** * 发送 ping 消息 */ sendPing() { Log.info('sendPing:'); const message = JSON.stringify({ data: 'node', type: 'ping' }); this.sendMessage(message); } /** * 发送消息到服务器 * @param {string} message - JSON 字符串 */ sendMessage(message) { // 检查连接状态 if (this.socket.readyState === WebSocket.OPEN) { this.socket.send(message); // 使用 send() 发送 Log.info('Sent:', message); } else { Log.error('WebSocket未连接或未就绪'); } } /** * 断开连接 */ disconnect() { if (this.socket) { this.socket.close(); // 使用 close() 方法 } } } SocketController.toString = () => '[class SocketController]'; module.exports = SocketController;