Dynamically Enable/Disable WebSocket node

Hello .. i think the core Websocket nodes connect and stay connected and i didnt see a way to force a disconnect.

You could load the ws library using the functionExternalModules option in a Function node as a workaround in order to have better control.

I dont know much about websockets but here's a flow to demostrate it using an online open test server.
(in this example when a msg with the expected data is received .. we force a disconnect )

[{"id":"6ff8ddd581cb52e0","type":"function","z":"54efb553244c241f","name":"","func":"const ws = new WebSocket('wss://demo.piesocket.com/v3/channel_1?api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm&notify_self');\nnode.status({ fill: \"green\", shape: \"dot\", text: \"Connected\" });\n// ws.onopen = function () {\n//     console.log('WebSocket Client Connected');\n//     ws.send('Hi this is web client.');\n// };\nws.onmessage = function (e) {\n  node.warn({ payload: e.data });\n\n  if (e.data.startsWith(\"cpu\")) {\n    node.warn(\"Msg received. Closing Websocket\");\n    node.status({ fill: \"red\", shape: \"dot\", text: \"Disconnected\" });\n    ws.close();\n  }\n\n};\n\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[{"var":"WebSocket","module":"ws"}],"x":470,"y":1120,"wires":[["a0a621998adc2697"]]},{"id":"98c5874423d2fd40","type":"inject","z":"54efb553244c241f","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":300,"y":1120,"wires":[["6ff8ddd581cb52e0"]]},{"id":"a0a621998adc2697","type":"debug","z":"54efb553244c241f","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":650,"y":1120,"wires":[]}]

ps. you can read how to setup functionExternalModules here

image