I have written a WebSocket code for creating WebSocket connections dynamically. Below is the custom node code.
module.exports = function(RED) {
var WebSocket = require('ws');
function CustomWebSocketListener(config) {
RED.nodes.createNode(this,config);
var node = this;
node.on('input', function(msg) {
let urls =msg.payload.urls;
let connections = {};
for(let k in connections) {
connections[k].close();
connections[k].reconnect=false
console.log('connection closed:::');
}
for(let i=0;i<urls.length;i++){
console.log(':::::::for loop:::::::')
console.log('url----'+urls[i])
function connect(urlIndex) {
let ws;
if(urlIndex!=undefined||urlIndex!=null){
ws = new WebSocket(urls[urlIndex]);
}
else{
ws = new WebSocket(urls[i]);
}
ws.index=i;
ws.reconnect=true;
ws.onopen = function() {
};
ws.onmessage = function(e) {
console.log('Message:', e.data);
msg.payload=e.data;
var log="Connected";
node.send({payload:log});
node.send(msg);
};
ws.onclose = function(e) {
var dis="Disconnected";
node.send({payload:dis})
var log_1="Socket is closed. Reconnect will be attempted in 30 second.";
//msg.payload=log_1;
node.send({payload:log_1});
console.log('Socket is closed. Reconnect will be attempted in 30 second.', e.reason);
setTimeout(function() {
console.log("onclose ----ws reconnect"+ws.reconnect)
if(ws.reconnect){
console.log("inside if reconnect")
connect(ws.index);
}
}, 30000);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
connections[urls[i]]=ws
}
connect();
}
});
}
RED.nodes.registerType("custom-websocketlistener",CustomWebSocketListener);
}
The above code will take an array of WebSocket url for creating connection and it will workfine as expected and reconnect also will happen as expected. But if I send one more request for new websocket with array of url, old connections it will disconnect and new connection will be created for the newly sent urls. So I what I want is, if the URL is same then it has to neglect and should not create a new connection and if the URL is different then only it should create a new connection. So, how can I handle the connection object at a global level or a standardized manner?