简体   繁体   中英

PM2 with NodeJS dgram

I am trying to run a NodeJS application(udp_recv) using pm2. The application starts on boot via pm2 startup and pm2 save. However, the dgram gives me an error saying -

server error:
1|udp_recv | Error: bind EADDRNOTAVAIL 192.168.0.9:7001
1|udp_recv |     at state.handle.lookup (dgram.js:242:18)
1|udp_recv |     at process._tickCallback (internal/process/next_tick.js:63:19)
1|udp_recv |     at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
1|udp_recv |     at startup (internal/bootstrap/node.js:283:19)
1|udp_recv |     at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

But once I stop all the application (pm2 stop all) and re-run (pm2 start all) Then there's no error and the application runs normally without any error.

My IP is 192.168.0.9 listening for UDP streams on a predefined port. The computer connected via ethernet sends the UDP streams from IP 192.168.0.6

Can someone tell me how to solve the error?

https://forums.balena.io/t/eaddrnotavail-when-trying-to-bind-socket-after-device-turns-back-on/4285

Turns out binding right after reboot via dgram can cause the error. Simply because "EADDRNOTAVAIL" means address not available.

Solution setTimeout on socket.bind to around 60 seconds and it'll work just fine.

setTimeout(() => {
    server.bind({
        address: "127.0.0.1",
        port: process.env.SERVER_PORT,
        exclusive : true
    })
}, 60000)

Also, another solution is to try to reconnect/rebind on server error "EADDRNOTAVAIL"

//If server(app.js) gets any error
server.on('error', (err) => {

    console.log(`server error:\n${err.stack}`);
    //Server is closed
    //server.close();

    //add an "if" block to check if the error is of type "EADDRNOTAVAIL"
    server.bind({
            address: "127.0.0.1",
            port: process.env.SERVER_PORT,
            exclusive : true
        })
});

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