socket.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. const { pyapp } = require('../config/app.config.json')
  8. class SocketController extends Controller {
  9. constructor(ctx) {
  10. super(ctx);
  11. }
  12. /**
  13. * Connect to WebSocket server
  14. */
  15. async connect() {
  16. await new Promise(async (resolve,reject) => {
  17. const win = CoreWindow.getMainWindow()
  18. if(socket){
  19. console.log('has socket ')
  20. resolve(true);
  21. win.webContents.send('controller.socket.connect_open', true);
  22. return;
  23. }
  24. socket = new WebSocket('ws://'+pyapp+':7074/ws');
  25. // 监听连接成功事件
  26. socket.on('open', () => {
  27. console.log('socket open')
  28. resolve(true);
  29. win.webContents.send('controller.socket.connect_open', true);
  30. });
  31. // 监听消息事件
  32. socket.on('message', (data) => {
  33. try {
  34. let this_data = JSON.parse(data.toString());
  35. console.log(this_data.msg_type);
  36. console.log(this_data);
  37. if(this_data.msg_type){
  38. let channel = 'controller.socket.message_'+this_data.msg_type;
  39. if(this_data.msg_type === 'run_mcu_single_finish' ){
  40. this.app.electron['seeting'].webContents.send(channel, this_data);
  41. }else{
  42. win.webContents.send(channel, this_data);
  43. }
  44. }
  45. }catch (e){
  46. console.log(e)
  47. }
  48. });
  49. // 监听连接关闭事件
  50. socket.on('close', () => {
  51. console.log('socket close');
  52. win.webContents.send('controller.socket.disconnect', null);
  53. socket = null
  54. });
  55. // 监听错误事件
  56. socket.on('error', (err) => {
  57. console.log('socket error');
  58. win.webContents.send('controller.socket.disconnect', null);
  59. reject(true);
  60. });
  61. console.log('socket end')
  62. })
  63. }
  64. /**
  65. * 发送 ping 消息
  66. */
  67. sendPing() {
  68. const message = JSON.stringify({ data: 'node', type: 'ping' });
  69. this.sendMessage(message);
  70. }
  71. /**
  72. * 发送消息到服务器
  73. * @param {string} message - JSON 字符串
  74. */
  75. sendMessage(message) {
  76. // 检查连接状态
  77. console.log(message);
  78. console.log(typeof socket);
  79. if (socket?.readyState === WebSocket.OPEN) {
  80. socket.send(message); // 使用 send() 发送
  81. } else {
  82. }
  83. }
  84. /**
  85. * 断开连接
  86. */
  87. disconnect() {
  88. if (socket) {
  89. socket.close(); // 使用 close() 方法
  90. socket = null;
  91. }
  92. }
  93. }
  94. SocketController.toString = () => '[class SocketController]';
  95. module.exports = SocketController;