Node red custom websocket how to handle connections

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?

1 Like

Hi, just curious, you know there is a websocket node in the node-red library (built in)?
I wonder why are you developing another? Is there some additional features you need? You might be better of collaborating with the maintainer? just a thought.

From node-red I am exposing a rest API where user will push the set of websocket url to be listened. Then this custom node will listen and push all the message to mqtt. Here listening is decided dynamically.

Hi VIKRAMAS, I have a need for dynamic websocket's and "followed" your code to create the custom node. However, I get error [object Object] after I add the node ether with npm link or npm install methods.
image

I get the same error following your previous post about your dynamic websocket node here: Custom node is not adding to Node-red

How did you manage to get it to work?

Realised that error was missing "module.exports = function(RED) {" as the start of the .js file.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.