Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.send outside of io.sockets.on( )

I have a loop that querys a database continuously. When the query returns a result, the node.js app will send a message to every client connected to the node server via socket.io v0.8.

Problem: io.sockets.broadcast.send('msg') is called in the middle of a setInterval() loop so it is not within an io.sockets.on()'s callback function and thus this will not work. When io.sockets.send('msg') is used, no message seems to be sent to the client.

Node.js code

setInterval(function() {     util.log('Checking for new jobs...');     dbCheckQueue(function(results) {         if (results.length) {             io.sockets.broadcast.send('hello');         }     }); }, 10*1000); 

However, if the setInterval is to be called from within io.sockets.on('connection',..), every connected client will create an additional loop!

Node.js code

io.sockets.on('connection', function(socket) {     setInterval(function() {         util.log('Checking for new jobs...');         dbCheckQueue(function(results) {             if (results.length) {                 io.sockets.send('hello');             }         });     }, 10*1000); }); 

Clientside JS

        socket.on('hello', function() {             console.log('HELLO received');         }) 

*How can I get a SINGLE loop to run, but still be able to send a message to all connected clients?

like image 995
Nyxynyx Avatar asked Nov 26 '11 20:11

Nyxynyx


People also ask

Is Socket.IO synchronous or asynchronous?

JS, Socket.IO enables asynchronous, two-way communication between the server and the client. This means that the server can send messages to the client without the client having to ask first, as is the case with AJAX.

Does Socket.IO auto reconnect?

In the first case, the Socket will automatically try to reconnect, after a given delay.

How does Soket IO work?

Socket.IO allows bi-directional communication between client and server. Bi-directional communications are enabled when a client has Socket.IO in the browser, and a server has also integrated the Socket.IO package. While data can be sent in a number of forms, JSON is the simplest.

How do I secure a Socket.IO connection?

All you have to do is updating the remote session store on node server when a new login/logout happens in your php server. Show activity on this post. The excellent passport framework for express uses secure cookies to validate identity. There is even a module to access it from socket.io.


1 Answers

I think that this will successfully solve your problem

io.sockets.emit('hello') 
like image 126
Nyxynyx Avatar answered Sep 28 '22 04:09

Nyxynyx