# Node red custom websocket how to handle connections

**URL:** <https://discourse.nodered.org/t/node-red-custom-websocket-how-to-handle-connections/24145>\
**Category:** General\
**Created:** [3 April 2020 11:10 UTC](https://discourse.nodered.org/t/node-red-custom-websocket-how-to-handle-connections/24145 "2020-04-03T11:10:23Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![VIKRAMAS](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/vikramas/32/3955_2.png) [@VIKRAMAS](https://discourse.nodered.org/u/VIKRAMAS)\
**Post date:** [3 April 2020 11:10 UTC](https://discourse.nodered.org/t/node-red-custom-websocket-how-to-handle-connections/24145/1 "2020-04-03T11:10:23Z")

</div>

I have written a WebSocket code for creating WebSocket connections dynamically. Below is the custom node code.

```auto
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?

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [3 April 2020 13:02 UTC](https://discourse.nodered.org/t/node-red-custom-websocket-how-to-handle-connections/24145/2 "2020-04-03T13:02:41Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![VIKRAMAS](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/vikramas/32/3955_2.png) [@VIKRAMAS](https://discourse.nodered.org/u/VIKRAMAS)\
**Post date:** [3 April 2020 13:05 UTC](https://discourse.nodered.org/t/node-red-custom-websocket-how-to-handle-connections/24145/3 "2020-04-03T13:05:23Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Serge](https://avatars.discourse-cdn.com/v4/letter/s/5f8ce5/32.png) [@Serge](https://discourse.nodered.org/u/Serge)\
**Post date:** [25 May 2020 08:15 UTC](https://discourse.nodered.org/t/node-red-custom-websocket-how-to-handle-connections/24145/4 "2020-05-25T08:15:40Z")

</div>

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](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/3/3/3302ddbc0725528a5064605e862d89c98ddff5eb.png)

I get the same error following your previous post about your dynamic websocket node here: [Custom node is not adding to Node-red](https://discourse.nodered.org/t/custom-node-is-not-adding-to-node-red/21475)

How did you manage to get it to work?

---

<div class="post-metadata">

**Author:** ![Serge](https://avatars.discourse-cdn.com/v4/letter/s/5f8ce5/32.png) [@Serge](https://discourse.nodered.org/u/Serge)\
**Post date:** [25 May 2020 10:05 UTC](https://discourse.nodered.org/t/node-red-custom-websocket-how-to-handle-connections/24145/5 "2020-05-25T10:05:48Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [8 June 2020 10:05 UTC](https://discourse.nodered.org/t/node-red-custom-websocket-how-to-handle-connections/24145/6 "2020-06-08T10:05:51Z")

</div>

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