Home > Mobile >  STDIN process and SOCKETS.IO
STDIN process and SOCKETS.IO

Time:07-24

I have a stream of decoded metadata coming from my local Node-Express server with the following code:

process.stdin.on('data', function (data) {
const result = klv.decode(data, standards, null, { payload: true, debug: process.argv[2] === 'debug' })
console.log(result);})

All good up to now. I cannot figure a way to send the stream of data to a client via sockets.io.

I have tried wrapping the above code into a async function name process_data using it like this:

io.on('connection', (socket) =>{
socket.emit('geolocation-data', process_data())});

No data is passing to the client.

I have also tried putting the socket inside my function like this:

async function process_data () {
    process.stdin.on('data', function (data) {
        const result = klv.decode(data, standards, null, { payload: true, debug: process.argv[2] === 'debug' });
        io.on('connection', (socket) =>{
            socket.emit('geolocation-data', result );
        })})};

In this case some data are passing to the client, but I need to refresh all the time, plus I get this error on my terminal:

(node:45139) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added to [Namespace]. Use emitter.setMaxListeners() to increase limit

What exactly is happening? Any code suggestions?

CodePudding user response:

let socketClients = [];
io.on('connection', (socket) =>{socketClients.push(socket)});
process.stdin.on('data', function (data) {
const result = klv.decode(data, standards, null, { payload: true, debug: 
process.argv[2] === 'debug' })
socketClients.forEach(s=>s.emit('geolocation-data',result ))
console.log(result);})

CodePudding user response:

The issue here is that you are only sending data on the connection event, which is why you need to refresh. You should be handling the connection to the client before you read anything in through stdin:

io.on('connection', (socket) => {
  process.stdin.on('data', function (data) {
    const result = klv.decode(data, standards, null, { payload: true, debug: process.argv[2] === 'debug' });
    socket.emit('geolocation-data', result);
});

This way you are connecting first, then sending data.

more about socket io emit events

  • Related