socket.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. const { Controller } = require('ee-core');
  3. const Log = require('ee-core/log');
  4. const CoreWindow = require('ee-core/electron/window');
  5. const WebSocket = require('ws'); // 引入原生 ws 库
  6. let socket = null;
  7. class SocketController extends Controller {
  8. constructor(ctx) {
  9. super(ctx);
  10. }
  11. /**
  12. * Connect to WebSocket server
  13. */
  14. connect() {
  15. socket = new WebSocket('ws://10.56.42.176:7074/ws');
  16. const win = CoreWindow.getMainWindow()
  17. // 监听连接成功事件
  18. socket.on('open', () => {
  19. return true;
  20. });
  21. // 监听消息事件
  22. socket.on('message', (data) => {
  23. win.webContents.send('controller.socket.message', data.toString());
  24. });
  25. // 监听连接关闭事件
  26. socket.on('close', () => {
  27. });
  28. // 监听错误事件
  29. socket.on('error', (err) => {
  30. });
  31. }
  32. /**
  33. * 发送 ping 消息
  34. */
  35. sendPing() {
  36. const message = JSON.stringify({ data: 'node', type: 'ping' });
  37. this.sendMessage(message);
  38. }
  39. /**
  40. * 发送消息到服务器
  41. * @param {string} message - JSON 字符串
  42. */
  43. sendMessage(message) {
  44. // 检查连接状态
  45. if (socket?.readyState === WebSocket.OPEN) {
  46. socket.send(message); // 使用 send() 发送
  47. } else {
  48. }
  49. }
  50. /**
  51. * 断开连接
  52. */
  53. disconnect() {
  54. if (socket) {
  55. socket.close(); // 使用 close() 方法
  56. socket = null;
  57. }
  58. }
  59. }
  60. SocketController.toString = () => '[class SocketController]';
  61. module.exports = SocketController;