Last active
September 12, 2018 10:44
-
-
Save kirrg001/f6ca630337b64f587c8c291f6f4e5ff4 to your computer and use it in GitHub Desktop.
bootstrap-test-client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const host = process.argv[3]; | |
const port = process.argv[5]; | |
const socketAddress = { | |
host: host || 'localhost', | |
port: port || 8989 | |
}; | |
const net = require('net'); | |
const client = new net.Socket(); | |
const start = (message) => { | |
return new Promise((resolve) => { | |
const connect = (options = {}) => { | |
let wasResolved = false; | |
const waitTimeout = setTimeout(() => { | |
console.log('Bootstrap socket timed out.'); | |
if (!client.destroyed) { | |
client.destroy(); | |
} | |
if (wasResolved) { | |
return; | |
} | |
wasResolved = true; | |
resolve(); | |
}, 1000 * 5); | |
client.connect(socketAddress.port, socketAddress.host, () => { | |
if (waitTimeout) { | |
clearTimeout(waitTimeout); | |
} | |
client.write(JSON.stringify(message)); | |
if (wasResolved) { | |
return; | |
} | |
wasResolved = true; | |
resolve(); | |
}); | |
client.on('close', () => { | |
console.log('Bootstrap client was closed.'); | |
if (waitTimeout) { | |
clearTimeout(waitTimeout); | |
} | |
}); | |
client.on('error', (err) => { | |
console.log(`Can\'t connect to the bootstrap socket (${socketAddress.host} ${socketAddress.port}) ${err.code}`); | |
client.removeAllListeners(); | |
if (waitTimeout) { | |
clearTimeout(waitTimeout); | |
} | |
if (options.tries < 3) { | |
console.log(`Tries: ${options.tries}`); | |
// retry | |
console.log('Retrying...'); | |
options.tries = options.tries + 1; | |
const retryTimeout = setTimeout(() => { | |
clearTimeout(retryTimeout); | |
connect(options); | |
}, 500); | |
} else { | |
if (wasResolved) { | |
return; | |
} | |
wasResolved = true; | |
resolve(); | |
} | |
}); | |
}; | |
connect({tries: 0}); | |
}); | |
}; | |
start({ | |
started: true | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment