MCPcopy Create free account
hub / github.com/Marus/cortex-debug / waitForPortOpenOSUtl

Method waitForPortOpenOSUtl

src/tcpportscanner.ts:256–298  ·  view source on GitHub ↗

* This is the most unobtrusive way of figuring out if a port is open. It does not try * to create servers or clients but use system commands to figure out if a port is open * On Mac, the runtime is not bad 1.5 to 2X of the time take to do it the other ways. * On windows, surprise!, it

(port: number, retryTimeMs = 100, timeOutMs = 5000, fallback = true, doLog = true)

Source from the content-addressed store, hash-verified

254 * @param fallback Fallback to using the intrusive method if proper OS command is not available
255 */
256 public static waitForPortOpenOSUtl(port: number, retryTimeMs = 100, timeOutMs = 5000, fallback = true, doLog = true): Promise<void> {
257 const cmd = TcpPortScanner.getOsNetProbeCmd().replace('XYZZY', port.toString());
258 logEnable = logEnable || doLog;
259 ConsoleLog(cmd);
260 if (fallback && (cmd === '?')) {
261 return TcpPortScanner.waitForPortOpen(port, TcpPortScanner.DefaultHost, true, retryTimeMs, timeOutMs);
262 }
263
264 const rexStr = TcpPortScanner.OSNetProbeCmdRegexpStr.replace('XYZZY', port.toString());
265 ConsoleLog(rexStr);
266 const rex = new RegExp(rexStr);
267 const startTimeMs = Date.now();
268 let first = true;
269 retryTimeMs = Math.max(retryTimeMs, 1);
270 return new Promise(function tryAgain(resolve, reject) {
271 if (cmd === '?') {
272 return reject(new Error('failed'));
273 }
274 child_process.exec(cmd, (error, stdout) => {
275 if (error && !cmd.startsWith('lsof')) {
276 // lsof returns an error code if nothing matches. May match later
277 return reject(error);
278 } else if (rex.test(stdout)) {
279 ConsoleLog(stdout.match(rex).join('\n'));
280 return resolve();
281 } else {
282 if (first) {
283 // ConsoleLog(stdout);
284 first = false;
285 }
286 const t = Date.now() - startTimeMs;
287 if (t < timeOutMs) {
288 ConsoleLog(`waitForPortOpenOSUtl: Setting timeout for ${retryTimeMs}ms, curTime = ${t}ms`);
289 setTimeout(() => {
290 tryAgain(resolve, reject);
291 }, retryTimeMs);
292 } else {
293 return reject(new Error('timeout'));
294 }
295 }
296 });
297 });
298 }
299
300 /**
301 * This is the workhorse function for all kinds of status queries on port:localhost

Callers 1

Calls 4

toStringMethod · 0.80
ConsoleLogFunction · 0.70
getOsNetProbeCmdMethod · 0.45
waitForPortOpenMethod · 0.45

Tested by

no test coverage detected