Working with WebSockets
Node-RED provides a type of node to handle WebSocket connectivity. The websocket in and websocket out node can be configured to listen on a WebSocket path as a server or connect to a URL as a client.
You can use WebSocket Events to enhance the functionality of your HTML pages. WebSocket events can be triggered by interacting with the webpage. They can start a flow to gather data or trigger other processes like writing to a database or starting a cyclic event.
To establish a WebSocket connection on your client page and send and receive data, you can use the following lines:
var ws = new WebSocket(`wss://${location.hostname}/ws/example`)
ws.send('data')
ws.onmessage = function(event){
var data = event.data
}
You can install additional nodes to handle WebSocket connections. Those might permanently destroy the current instance of the Flow App you are working on. For Example: one of the most famous Libraries for WebSocket connections is Socket.IO. It can be imported as a set of nodes. It can be set to run on a different port, which will not be allowed by the server. Running a Socket.IO server on the same port as Node-RED will crash the instance or block access to the pages hosted through Node-RED, including the editor.