简体   繁体   中英

Node.js: Race condition when receiving data on tcp socket

I'm using the net library of Node.js to conect to a server that is publishing data. So I'm listening for 'data'-events on client side. When the data-event is fired, I append the received data to my rx-buffer and check if we got a complete message by reading some bytes. If I got a valid message, I remove the message from the buffer and process it. The source code looks like:

rxBuffer = ''

client.on('data', (data) => {
  rxBuffer += data

  // for example... 10 stores the message length...
  while (rxBuffer.length > 10 && rxBuffer.length >= (10 + rxBuffer[10])) {
    const msg = rxBuffer.slice(0, 10 + rxBuffer[10])
    rxBuffer = rxBuffer.slice(0, msg.length) // remove message from buffer
    processMsg(msg) // process message..
  }
})

As far as I know that the typical way. But... what happens if the data event fired multiple times? So, imagine I'm getting a data event and while I append the data to my rx-buffer I'm getting the next data event. So the "new" data event will also append the data to the rxBuffer and starts my while-loop. So I've two handlers that are processing the same messages because they share the same rx-buffer. Is this correct? How can I handle this? In other languages I'd say use something like a mutex to prevent multiple access to the rx-buffer... but what's the solution forjs?!?! Or maybe I'm wrong and I'm never getting multiple data-events while one event is still active? Any ideas?

JavaScript is single threaded. The second event will not run until the first one either completes or blocks, the latter of which could presumably happen in your processMsg() . If that's the case, multiple executions of processMsg() could be interleaved. If they aren't changing any global data ( rxBuffer included), then you shouldn't have a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM