Created
November 18, 2019 04:34
-
-
Save mrubiosan/be51410e7b60cc2734e2fdd4a1b1fca9 to your computer and use it in GitHub Desktop.
Nodejs Socket wrapper for auto-reconnection
This file contains hidden or 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
import Timeout = NodeJS.Timeout; | |
import { Socket, NetConnectOpts } from "net"; | |
function attachReconnectOnError(socket: Socket, options: NetConnectOpts, retryMs: number): void { | |
let timerId: Timeout | null; | |
const clear = () => { | |
if (timerId !== null) { | |
clearTimeout(timerId); | |
timerId = null; | |
} | |
}; | |
socket.addListener('close', (hadError: boolean) => { | |
if (hadError) { | |
timerId = setTimeout(() => { | |
socket.connect(options) | |
}, retryMs); | |
} else { | |
clear(); | |
} | |
}); | |
socket.addListener('connect', clear); | |
// For this to work errors need to be captured | |
socket.addListener('error', () => undefined); | |
} | |
export function createConnection(options: NetConnectOpts, connectListener?: () => void, retryMs?: number): Socket; | |
export function createConnection(path: string, connectListener?: () => void, retryMs?: number): Socket; | |
export function createConnection(port: number, host?: string, connectListener?: () => void, retryMs?: number): Socket; | |
export function createConnection(firstArg, ...otherArgs): Socket { | |
let options: NetConnectOpts; | |
let connectListener: () => void; | |
let retryMs; | |
if (typeof firstArg === 'string') { | |
options = { | |
path: firstArg, | |
}; | |
connectListener = otherArgs[0]; | |
retryMs = otherArgs[1]; | |
} else if (typeof firstArg === 'number') { | |
options = { | |
port: firstArg, | |
host: otherArgs[0], | |
}; | |
connectListener = otherArgs[1]; | |
retryMs = otherArgs[2]; | |
} else if (typeof firstArg === 'object') { | |
options = firstArg; | |
connectListener = otherArgs[0]; | |
retryMs = otherArgs[1]; | |
} | |
const socket = new Socket(options); | |
retryMs = typeof retryMs === 'number' ? retryMs : 1000; | |
attachReconnectOnError(socket, options, retryMs); | |
return socket.connect(options, connectListener); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment