socket-connecting.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. // WebSocket Server
  2. // For matting-server connection
  3. const WebSocket = require('ws');
  4. const WS_PORT = 9527;
  5. // WebSocket server instance
  6. let wss = null;
  7. // Matting server client connection
  8. let mattingClient = null;
  9. // Pending callbacks map
  10. const pendingCallbacks = new Map();
  11. /**
  12. * Start WebSocket Server
  13. */
  14. function startWebSocketServer() {
  15. if (wss) {
  16. console.log('[WebSocket] Server already running');
  17. return;
  18. }
  19. wss = new WebSocket.Server({ port: WS_PORT });
  20. wss.on('listening', () => {
  21. console.log(`[WebSocket] Server listening on port: ${WS_PORT}`);
  22. });
  23. wss.on('connection', (ws, req) => {
  24. const clientIP = req.socket.remoteAddress;
  25. console.log(`[WebSocket] New connection: ${clientIP}`);
  26. mattingClient = ws;
  27. ws.on('message', (data) => {
  28. try {
  29. // Binary format: 4-byte filename length + filename + zip data
  30. if (Buffer.isBuffer(data)) {
  31. const filenameLen = data.readUInt32BE(0);
  32. const filename = data.slice(4, 4 + filenameLen).toString('utf-8');
  33. const zipData = data.slice(4 + filenameLen);
  34. console.log(`[WebSocket] Received: ${filename}, size: ${zipData.length} bytes`);
  35. // Find and execute callback
  36. const callback = pendingCallbacks.get(filename);
  37. if (callback) {
  38. pendingCallbacks.delete(filename);
  39. callback(null, zipData);
  40. } else {
  41. console.warn(`[WebSocket] No callback found for: ${filename}`);
  42. }
  43. } else {
  44. console.log(`[WebSocket] Received text: ${data}`);
  45. }
  46. } catch (error) {
  47. console.error('[WebSocket] Message handling error:', error);
  48. }
  49. });
  50. ws.on('close', () => {
  51. console.log('[WebSocket] Connection closed');
  52. if (mattingClient === ws) {
  53. mattingClient = null;
  54. }
  55. });
  56. ws.on('error', (error) => {
  57. console.error('[WebSocket] Connection error:', error);
  58. });
  59. });
  60. wss.on('error', (error) => {
  61. console.error('[WebSocket] Server error:', error);
  62. });
  63. }
  64. /**
  65. * Check if matting-server is connected
  66. * @returns {boolean}
  67. */
  68. function isMattingServerConnected() {
  69. return mattingClient !== null && mattingClient.readyState === WebSocket.OPEN;
  70. }
  71. /**
  72. * Send matting task to matting-server
  73. * @param {string} taskId - Task ID (used as filename)
  74. * @param {Buffer} zipData - ZIP data buffer
  75. * @param {Function} callback - Callback function (error, resultZipData)
  76. * @param {number} timeout - Timeout in milliseconds (default 5 minutes)
  77. */
  78. function sendMattingTask(taskId, zipData, callback, timeout = 5 * 60 * 1000) {
  79. if (!isMattingServerConnected()) {
  80. callback(new Error('matting-server not connected'));
  81. return;
  82. }
  83. try {
  84. // Binary format: 4-byte filename length + filename + zip data
  85. const filenameBytes = Buffer.from(taskId, 'utf-8');
  86. const lenBuffer = Buffer.alloc(4);
  87. lenBuffer.writeUInt32BE(filenameBytes.length, 0);
  88. const message = Buffer.concat([lenBuffer, filenameBytes, zipData]);
  89. // Register callback
  90. pendingCallbacks.set(taskId, callback);
  91. // Set timeout
  92. const timeoutId = setTimeout(() => {
  93. if (pendingCallbacks.has(taskId)) {
  94. pendingCallbacks.delete(taskId);
  95. callback(new Error('VIP matting request timeout'));
  96. }
  97. }, timeout);
  98. // Wrap callback to clear timeout
  99. const originalCallback = callback;
  100. pendingCallbacks.set(taskId, (error, data) => {
  101. clearTimeout(timeoutId);
  102. originalCallback(error, data);
  103. });
  104. // Send message
  105. mattingClient.send(message);
  106. console.log(`[WebSocket] Sent task: ${taskId}, size: ${message.length} bytes`);
  107. } catch (error) {
  108. pendingCallbacks.delete(taskId);
  109. callback(error);
  110. }
  111. }
  112. /**
  113. * Stop WebSocket Server
  114. */
  115. function stopWebSocketServer() {
  116. if (wss) {
  117. wss.close(() => {
  118. console.log('[WebSocket] Server stopped');
  119. });
  120. wss = null;
  121. mattingClient = null;
  122. }
  123. }
  124. // Auto-start WebSocket Server
  125. startWebSocketServer();
  126. module.exports = {
  127. startWebSocketServer,
  128. stopWebSocketServer,
  129. isMattingServerConnected,
  130. sendMattingTask
  131. };