dresende / node-modbus-tcp

NodeJS Modbus TCP/IP
MIT License
117 stars 48 forks source link

Proper way to destroy modbus client object #25

Closed Nedgeva closed 7 years ago

Nedgeva commented 7 years ago

My modbus TCP server device (actually it's ABB AC500 series PLC) closes connection after data was send, so i need to make new socket connection to PLC every time i want to read/write data from/to PLC, e.g. to keep polling mbus registers (or coils, whatever). This question seems to be close to https://github.com/dresende/node-modbus-tcp/issues/23 but in my case 'simply piping new socket to old modbus stream consumer' leads to memory leaking (both RSS and heap keep growing). I've tried to unpipe both sides (reader and writer), destroy streams - same result. My current workaround is to wrap instantiated socket and modbus clients into object and then after they are finished their job, just null object entries and delete them to make sure that there are no more streams hanging around:

const netModule = {
  mbClient: new modbus.Client(),
  socket: new net.Socket({ 
    allowHalfOpen: false,
    readable: true,
    writable: true
  })
}

const streams = {
  writer: netModule.mbClient.writer(),
  reader: netModule.mbClient.reader()
}

// burn em after using
const unrefObjKeys = obj =>
  Object.keys(obj).forEach(key => {
    obj[key] = null
    delete obj[key]
  })

unrefObjKeys(netModule)
unrefObjKeys(streams)

This workaround fixes memory leaking, but looking pretty dirty, right?

dresende commented 7 years ago

Hi, I no longer maintain this repo. Try the new version which handles all kinds of modbus.

https://github.com/node-modbus/stream

Also, it has a proper method for closing streams.