From Beefy Earthworm, 2 Months ago, written in JavaScript.
  1. const WebSocket = require('ws');
  2. const fs = require('fs');
  3. const path = require('path');
  4.  
  5. // Define the output file path
  6. const outputFilePath = path.join(__dirname, 'received_stereo_audio.raw');
  7.  
  8. // Create a writable stream to the output file
  9. const writeStream = fs.createWriteStream(outputFilePath, { flags: 'w' }); // 'a' flag for appending
  10.  
  11. // Create a WebSocket server
  12. const wss = new WebSocket.Server({ port: 8080 });
  13.  
  14. wss.on('connection', (ws) => {
  15.     console.log('Client connected');
  16.  
  17.     ws.on('message', (message) => {
  18.         // We expect binary data (ArrayBuffer)
  19.         if (typeof message === 'object' && message instanceof Buffer) {
  20.             // Write the received data directly to the file
  21.             writeStream.write(message);
  22.             console.log(`Received ${message.length} bytes of stereo audio data and wrote to file`);
  23.         }
  24.     });
  25.  
  26.     ws.on('close', () => {
  27.         console.log('Client disconnected');
  28.     });
  29. });
  30.  
  31. // Handle server close to properly close the file stream
  32. wss.on('close', () => {
  33.     writeStream.end(); // Close the file stream
  34.     console.log('WebSocket server closed, file stream ended');
  35. });
  36.  
  37. console.log('WebSocket server is listening on ws://localhost:8080');
  38.