Last active
December 22, 2021 07:33
-
-
Save zemuldo/29053b277f28a275b2e15c041179d814 to your computer and use it in GitHub Desktop.
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 net = require('net'); | |
const client = new net.Socket(); | |
const config = { | |
host: '0.0.0.0', | |
port: 9670, | |
exclusive: true, | |
} | |
const timeout = 3000; | |
let retrying = false; | |
// Functions to handle client events | |
// connector | |
function makeConnection() { | |
client.connect(config.port, config.host); | |
} | |
function connectEventHandler() { | |
console.log('***** connected ******'); | |
console.log({ | |
port: client.remotePort, | |
host: client.remoteAddress, | |
}, 'connected to server'); | |
retrying = false; | |
} | |
function errorEventHandler(e) { | |
console.log(`Connection error ${e.code}`); | |
if (!retrying) { | |
retrying = true; | |
} | |
setTimeout(makeConnection, timeout); | |
} | |
function closeEventHandler() { | |
if (retrying) return false; | |
console.log('Server closed'); | |
console.log(`Reconnecting... in ${timeout / 1000} Seconds`); | |
if (!retrying) { | |
retrying = true; | |
} | |
return setTimeout(makeConnection, timeout); | |
} | |
// Start Eevent Listeners | |
client.on('connect', connectEventHandler); | |
client.on('error', errorEventHandler); | |
client.on('close', closeEventHandler); | |
// Connect to remote server | |
console.log('***** connecting ******'); | |
makeConnection(); | |
module.exports = client; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment