Cloud-Automation / node-modbus

Modbus TCP Client/Server implementation for Node.JS
456 stars 169 forks source link

How can I write the reconnection code? #282

Closed ilkcantnriverdi closed 2 years ago

ilkcantnriverdi commented 3 years ago

Hello, when the connection is lost, I want to reconnect instead of closing the program. When I run this code I get this error. How can I write the reconnection code?

reconnect

stefanpoeter commented 3 years ago

Check out this repository https://github.com/Cloud-Automation/node-net-reconnect, it handles tcp reconnection outside of the jsmodbus module.


    let options = { 
      'host' : 'somehost', 
      'port' : someport,
      'retryTime' : 1000, // 1s for every retry
      'retryAlways' : true // retry even if the connection was closed on purpose
    }
    let Reconnect = require('node-net-reconnect')
    let recon = new Reconnect(socket, options)

    socket.connect(options)

    socket.on('connect', function () {

      /* if you enabled retryAlways, a call to 
         socket.end() will reconnect the client.
         In that case you need to close the connection
         through the recon.end() method. */
      setTimeout(function () {
        recon.end()
      }, 10000)

    })```
ilkcantnriverdi commented 3 years ago

Thank you for your interest. I got such an error while installing the library. npmerr

stefanpoeter commented 3 years ago

Yes, it is implemented using linux. Cannot say anything for the windows part, sorry.

ilkcantnriverdi commented 3 years ago

I got it. Can you suggest a different solution?

stefanpoeter commented 3 years ago

I find tcp socket state handling always annoying but I am sure I wasn't the only who needed to monitor socket states. I am sure a google search or a query on npm will give you something. I also think that extending the node-net-reconnect module for windows cannot be such a big deal.