Parker Lusk
Parker Lusk

Reputation: 158

NodeJS, Express, and eventful Socket.io

I want to build a NodeJS API so that when I hit an endpoint, the app will trigger an event that will cause its unique socket connection to emit a message to its listeners. I have built a solution before using Python/Django, Redis, and NodeJS/Socket.io with Django as the API and Redis as the 'event trigger', but I would like to consolidate the different technologies into NodeJS and Socket.io.

I tried moving the socket.emit() code into different modules and then app.use()'d those modules, but the code broke because it didn't have an instance of the socket.

I also know that you can broadcast to all socket connections inside on an endpoint, for example:

app.use('socket.io/help', function(req, res) {
    console.log(req.query);
    io.sockets.emit('help_message', 'You should help me.');

    res.send('help msg sent');
});

But I am looking for a way that allows a client (that doesn't have a socket connection) to hit an endpoint and pass a query param that tells NodeJS which of its connected sockets to send a message to.

Is this possible? Or am I trying to fight the framework? e.g., is there a different way of doing this with different JS WebSocket frameworks/technologies?

Upvotes: 0

Views: 1620

Answers (2)

Muhammad Ali
Muhammad Ali

Reputation: 2014

I have been stuck on same situation but resolved easily

you have created socket on app.js

server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(port);
global.socketIO = io;

Now you can call this io instance to your any controller like

app.use('socket.io/help', function(req, res) {
console.log(req.query);
 var io = global.socketIO;
 // UID IS THE VARIABLE
 io.sockets.emit('help_message'+UID, 'You should help me.');
 res.send('help msg sent');
});

CLIENT SIDE

<script src="/socket.io/socket.io.js"></script>
 <script>
window.socket.on("help_message_<%-UID%>", function(msg){ 
//// ACTION
 });

Upvotes: 4

Michael
Michael

Reputation: 1322

You can join a room with the specific sockets you want to recieve the messages on.

see Rooms & Namespaces in the socket.io documentation

join a chan on your helpdesk conenctions:

io.on('connection', function(socket){
  socket.join('helpdesk');
});

and broadcast to them:

app.use('socket.io/help', function(req, res) {
    console.log(req.query);
     var io = global.socketIO;
     io.sockets.emit('adduser', req.body.uid);
     io.to('helpdesk').emit('some event'):
     res.send('help msg sent');
});

Upvotes: 1

Related Questions