| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- '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 库
- let socket = null;
- class SocketController extends Controller {
- constructor(ctx) {
- super(ctx);
- }
- /**
- * Connect to WebSocket server
- */
- connect() {
- socket = new WebSocket('ws://10.56.42.176:7074/ws');
- const win = CoreWindow.getMainWindow()
- // 监听连接成功事件
- socket.on('open', () => {
- return true;
- });
- // 监听消息事件
- socket.on('message', (data) => {
- win.webContents.send('controller.socket.message', data.toString());
- });
- // 监听连接关闭事件
- socket.on('close', () => {
- });
- // 监听错误事件
- socket.on('error', (err) => {
- });
- }
- /**
- * 发送 ping 消息
- */
- sendPing() {
- const message = JSON.stringify({ data: 'node', type: 'ping' });
- this.sendMessage(message);
- }
- /**
- * 发送消息到服务器
- * @param {string} message - JSON 字符串
- */
- sendMessage(message) {
- // 检查连接状态
- if (socket?.readyState === WebSocket.OPEN) {
- socket.send(message); // 使用 send() 发送
- } else {
- }
- }
- /**
- * 断开连接
- */
- disconnect() {
- if (socket) {
- socket.close(); // 使用 close() 方法
- socket = null;
- }
- }
- }
- SocketController.toString = () => '[class SocketController]';
- module.exports = SocketController;
|