简体   繁体   中英

Callback was already calleld with async.parallel function

I am writing a simple port scanner using core net module from Node.js. I am getting a 'Callback was already called' error with my code. Can you spot please where the error is coming from? Below is my code:

 const net = require('net') const async = require('async') function findPortStatus(host, port, timeout, cb) { const socket = new net.Socket() socket.setTimeout(timeout, () => { // couldn't establish a connection because of timeout socket.destroy() return cb(null, null) }) socket.connect(port, host, () => { // connection established return cb(null, port) }) socket.on('error', (err) => { // couldn't establish a connection return cb(null, null) }) } const funcs = [] for (let port = 0; port <= 80; port++) { funcs.push(function(callback) { findPortStatus('192.30.253.112', port, 4000, (err, port) => { if (!err) { return callback(null, port) } }) }) } async.parallel(funcs, (err, ports) => { if (err) { console.error(err.message) } else { for (let port of ports) { if (port) { console.log(port) } } } }) 

Not sure if this is related, but you really should pass something to the callback when you call it. null,null isn't very useful for debugging. What I would suggest is timeout events in your context are probably not errors, but they are informative. You could just cb(null, 'timeout') or cb(null, {state: 'timedOut', port: port}) or something to better keep track of what worked and what didn't.

The most likely candidate for your actual error, though, is if your socket emits an error or timeout event after the connect event was already successful. Dropped connection or the like. If all you're looking for is a 'ping'-like functionality (across more than just ICMP obviously), then you should probably close the connection as soon as you get a connect and/or remove the other event listeners as part of the connect listener's handler.

Finally, the node docs suggest you not call socket.connect() directly, unless implementing a custom socket (which it doesn't seem like you are), but to use net.createConnection() instead; not sure that'll help you but it's worth noting.

It looks like the successfully connected sockets are subsequently timing out (which makes sense, as you connect but then do nothing with the connection, so it times out).

If you disconnect from a socket once you have recorded a successful connection, then that should clear up the error.

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