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) {
        var node = this;
        node.on('input', function(msg) {
			let urls =msg.payload.urls;
			let connections = {};
			for(let k in connections) {
			   console.log('connection closed:::');
			for(let i=0;i<urls.length;i++){
			console.log(':::::::for loop:::::::')
			function connect(urlIndex) {
				let ws;
					ws = new WebSocket(urls[urlIndex]);
					ws = new WebSocket(urls[i]);	
				ws.onopen = function() {

			  ws.onmessage = function(e) {
					var log="Connected";

			  ws.onclose = function(e) {
				  var dis="Disconnected";
				  var log_1="Socket is closed. Reconnect will be attempted in 30 second.";
				console.log('Socket is closed. Reconnect will be attempted in 30 second.', e.reason);
				setTimeout(function() {
					console.log("onclose ----ws reconnect"+ws.reconnect)
						console.log("inside if reconnect")
				}, 30000);

			  ws.onerror = function(err) {
				console.error('Socket encountered error: ', err.message, 'Closing socket');

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.

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.