I am trying to handle multiple client streams to write to different files at a time. Once a connection is established with a websocket and stream content is being written, as soon as the second connection is established the first write is stopped. Can someone help how to handle this in nodejs?
Here is the code snippet
const WebSocket = require('ws');
const fs = require('fs');
const argv = require('minimist')(process.argv.slice(2));
const recordingPath = argv._.length ? argv._[0] : '/tmp/';
const port = argv.port && parseInt(argv.port) ? parseInt(argv.port) : 3001
let wstream;
console.log(`listening on port ${port}, writing incoming raw audio to folder ${recordingPath}`);
const wss = new WebSocket.Server({
port,
handleProtocols: (protocols, req) => {
return 'audiostream.drachtio.org';
}
});
let conn = 1;
wss.on('connection', (ws, req) => {
console.log(`received connection from ${req.connection.remoteAddress}`);
const recordingPath = argv._.length ? argv._[0] : '/tmp/audio'+ Math.round((new Date()).getTime() / 1000) +'.raw';
console.log(`writing to path ${recordingPath} for connection ${conn}`);
wstream = fs.createWriteStream(recordingPath);
ws.on('message', (message) => {
if (typeof message === 'string') {
} else if (message instanceof Buffer) {
wstream.write(message);
}
});
conn++;
ws.on('close', (code, reason) => {
console.log(`socket closed ${code}:${reason}`);
wstream.end();
});
});