Communicating with Socket.IO from a Node-RED Function Node

Hi everyone,

I'm working on a custom Node-RED module using socket.io. I’ve defined a ui_base.js file where I set up a Socket.IO server and handle events. Here’s a snippet of my server-side code:

    socket.on('disconnect-request', (targetSocketId) => {
        const targetSocket = uiShared.ioServer.sockets.sockets.get(targetSocketId);
        if (targetSocket) {
            targetSocket.disconnect(true); // Disconnect the target socket
            console.log(`Socket ${targetSocketId} has been disconnected`);
        } else {
            console.log(`Socket ${targetSocketId} not found`);
        }
    });

    socket.on('custom-event', (data) => {
        console.log('Received data:', data);
        socket.emit('server-response', { message: 'Acknowledged', data });
    });
});

I'm trying to emit a custom-event from a Node-RED Function node like this:

const data = { message: 'Hello, server!' };
socket.emit('custom-event', data);
However, I'm not receiving any response back from the server.

I’ve also tried emitting the event inside a socket.on('connect', ...) block, but I still don’t see any progress.

Could anyone suggest how to establish communication between the Function node and the Socket.IO server? Am I missing something in the setup?

Thank you in advance for your help!

List item

Not at my best today (Christmas virus) so I might have missed something obvious, sorry if that is the case, someone will hopefully correct me if so.

You should probably set up your own custom event handling and make this available to function nodes by attaching the methods to RED.util - but PLEASE make sure that you use a property name that is absolutely unique and likely to remain so. For example, RED.util.socketOn would be a DREADFULL name but RED.util.subavarsha.socketOn would be rather better.

The best way to attach custom functions to the function node is likely to be via a separate plugin (which is like another node but without some of the unnecessary features).

You could instead make use of Node-RED's existing custom events process but again make sure that your event names will always be unique. Then your node could listen for the appropriate event and pass the data into a Socket.IO callback.

Another possible way might be to grab a reference to your main node and then call a function from it.


I don't recommend exposing Socket.IO functions direct to the function node, too much could go wrong and it would likely be a serious security issue. Remember - ALWAYS check user input. A Function node IS user input.

UIBUILDER has a lot of Socket.IO processing embedded. I've never needed a client connection on the server but I do pass one to the browser.