socket.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. class SocketController extends Controller {
  7. constructor(ctx) {
  8. super(ctx);
  9. this.socket = null;
  10. }
  11. /**
  12. * Connect to WebSocket server
  13. */
  14. connect() {
  15. this.socket = new WebSocket('ws://10.56.42.176:7074/ws');
  16. // 监听连接成功事件
  17. this.socket.on('open', () => {
  18. Log.info('Connected to WebSocket server');
  19. this.sendPing(); // 连接成功后发送 ping
  20. });
  21. // 监听消息事件
  22. this.socket.on('message', (data) => {
  23. Log.info('Received:', data.toString());
  24. });
  25. // 监听连接关闭事件
  26. this.socket.on('close', () => {
  27. Log.info('Disconnected from WebSocket server');
  28. });
  29. // 监听错误事件
  30. this.socket.on('error', (err) => {
  31. Log.error('WebSocketError:', err);
  32. });
  33. setInterval(()=>{
  34. const win = CoreWindow.getMainWindow();
  35. win.webContents.send('controller.socket.message', '这是一个消息');
  36. },2000)
  37. }
  38. /**
  39. * 发送 ping 消息
  40. */
  41. sendPing() {
  42. Log.info('sendPing:');
  43. const message = JSON.stringify({ data: 'node', type: 'ping' });
  44. this.sendMessage(message);
  45. }
  46. /**
  47. * 发送消息到服务器
  48. * @param {string} message - JSON 字符串
  49. */
  50. sendMessage(message) {
  51. // 检查连接状态
  52. if (this.socket.readyState === WebSocket.OPEN) {
  53. this.socket.send(message); // 使用 send() 发送
  54. Log.info('Sent:', message);
  55. } else {
  56. Log.error('WebSocket未连接或未就绪');
  57. }
  58. }
  59. /**
  60. * 断开连接
  61. */
  62. disconnect() {
  63. if (this.socket) {
  64. this.socket.close(); // 使用 close() 方法
  65. }
  66. }
  67. }
  68. SocketController.toString = () => '[class SocketController]';
  69. module.exports = SocketController;