slavery-js
Version:
A simple clustering app that allows you to scale an application on multiple thread, containers or machines
46 lines (40 loc) • 1.65 kB
text/typescript
import { log } from './index.js';
import { Connection } from '../network/index.js';
/**
* Checks if a Socket.IO server is running at the specified host and port.
* @param host - The hostname or IP address of the server.
* @param port - The port number on which the server is expected to be listening.
* @param timeout - The maximum time to wait for a response from the server, in milliseconds.
* @returns A promise that resolves to true if the server is running, otherwise false.
*/
async function isServerActive({ name, host, port, timeout }: {
name?: string, host: string, port: number, timeout?: number
}): Promise<boolean> {
return new Promise((resolve) => {
const connection = new Connection({
host,
port,
id: 'connection_test' + Math.random(),
timeout: 10000, // Increased timeout (e.g. 10 seconds)
onConnect: (connection: Connection) => {
resolve(true);
connection.close();
}
});
connection.on('connect_error', () => {
log(`Connection error to ${name} at ${host}:${port}`);
});
connection.on('connect_timeout', () => {
log(`Connection timeout to ${name} at ${host}:${port}`);
resolve(false);
connection.close();
});
connection.connected();
// Optional: set a manual timeout fallback, in case events fail to fire
setTimeout(() => {
resolve(false);
connection.close();
}, 12000); // fallback timeout longer than socket timeout
});
}
export default isServerActive