You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.8 KiB
JavaScript
61 lines
1.8 KiB
JavaScript
const WebSocket = require('ws');
|
|
const websocketServerNodes = require('../../config').websockets;
|
|
|
|
module.exports = callService => {
|
|
let connections = [];
|
|
|
|
const connect = () => {
|
|
websocketServerNodes.forEach((node, index) => {
|
|
createConnection(node, index);
|
|
});
|
|
};
|
|
|
|
const createConnection = (node, index) => {
|
|
try {
|
|
const ws = new WebSocket(node.host, [node.protocol]);
|
|
ws.on('open', () => {
|
|
console.log(`Connected to WebSocket ${index}: ${node.protocol} ${node.host} ${node.protocol}`);
|
|
// connections.push(ws);
|
|
connections = [...connections, ws];
|
|
console.log('Current connections:', connections.length);
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
console.log(`WebSocket ${index} disconnected. Reconnecting...`);
|
|
connections.splice(connections.indexOf(ws), 1);
|
|
setTimeout(() => createConnection(node, index), 3000);
|
|
});
|
|
|
|
ws.on('error', error => {
|
|
console.error(`WebSocket ${index} error:`, error);
|
|
});
|
|
|
|
ws.on('message', message => {
|
|
console.log(`Received from WebSocket ${index}: ${message}`);
|
|
});
|
|
} catch (error) {
|
|
console.error(`Error connecting to WebSocket ${index}:`, error);
|
|
}
|
|
};
|
|
|
|
const getAvailableConnection = () => {
|
|
// console.log('Available connections length:', connections.length);
|
|
for (const ws of connections) {
|
|
// console.log('Session has ws:', callService.sessions.has(ws));
|
|
if (!callService.sessions.has(ws)) {
|
|
// console.log('Found available ws:', ws); // Add this line
|
|
return ws;
|
|
}
|
|
}
|
|
console.log('No available connections found.');
|
|
return null;
|
|
};
|
|
const getConnections = () => connections; // Add this getter
|
|
|
|
return {
|
|
connect,
|
|
getAvailableConnection,
|
|
getConnections,
|
|
};
|
|
};
|