I am implementing socket.io in node.js for a Windows Azure project. I have to send data to all the connected clients at regular intervals.
I am new to node.js but I guess multi-threading is not possible. The purpose of socket.io is to support real-time applications, so is there any way that I can send data continuously to all my connected clients at regular intervals and also process whatever data the clients send to the socket.io server simultaneously?
EDIT:
This is roughly my socket.io implementation
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('first', "connected");
socket.on('clientData', function (data) {
//processing the data
});
});
function requestQueue() {
// some processing
io.sockets.emit('broadcast', recordsQueue);
// should go to sleep for a time period
}
Essentially I want the requestQueue method to be running continuously like a thread, which will emit data to connected clients at particular intervals. And also if the client sends any data to "clientData" event, then I should be able to receive the data and process it.
Any idea on how I can do it?
Thanks
My solution:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('first', "connected");
socket.on('clientData', function (data) {
//processing the data
});
});
function requestQueue() {
var sleepTime = 0;
// calcuate sleepTime
io.sockets.emit('broadcast', recordsQueue);
// should go to sleep for a time period
if(sleepTime !=0)
setTimeout(function () { requestQueue() }, sleepTime);
}
As others have suggested, you can achieve this by using the setInterval
or setTimeout
functions to periodically emit data to connected clients. Although everything runs within the same controlling thread, all of the I/O is done asynchronously so your application will still be responsive. IE, any data received while the timer is running will be queued up and processed after the timer function returns.
See Timers in the node.js manual for more information.
On a side note, you will want to have your node.js application focus on processing asynchronous I/O in near real-time as that is the strength of node.js. If you need to do any heavy computations then you will want to offload that to another thread/process somehow, by simply making an async request for the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With