简体   繁体   中英

Multi threading in Node.js?

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);
}

You are right, node is single threaded. But it makes heavy use of events.

The strategy you should go for is to listen for events on the connections, to retrieve data, and when you wish to send data back you do it because another event has been emitted.

If you take a look at the examples on the socket.io frontpage, you will see how they use events to start processing the streams. The on(eventName, function) method is how you listen for an event in NodeJS.

If you wish to do something based on timing (generally a bad idea), take a look at the setInterval method.

Server

    var io = require('socket.io').listen(80);

    io.sockets.on('connection', function (socket) {
      socket.emit('news', { hello: 'world' });
      socket.on('my other event', function (data) {
        console.log(data);
      });
    });

Client

    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io.connect('http://localhost');
      socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
      });
    </script>

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.

There is also a Node.js library for doing threads: node-webworker-threads

https://github.com/audreyt/node-webworker-threads

This basically implements the Web Worker browser API for node.js.

Note that this does not align with node.js's philosophy of single threadedness, but it's there if you need it.

The logic you define inside the setInterval etc. won't be working in a separate thread and eventually blocking the main. Let's say there are 1000 users and you called the setTimeout etc. for 1000 times, eventually they will be running and spending that precious time. Only the final IO operations are none-blocking!

You may consider investigating nodeJX for multithreading in node.js

Multi threading in Node.js?

Yes ..it is possible in nodejs using npm module 'java4node', it this package a method is .multiThreading(tasks , callbacks) This Function is use for perform multithreading in java script manner

for using this module link: https://www.npmjs.com/package/java4node

run commend

npm install java4node

var java = require('java4node')

java.multiThreading({
           one: function(callback,parameters) {
               console.log("function one is running independently");
               callback()
           },
           two: function(callback,parameters) {
                console.log("function two is running independently");
               callback()
           },
           three: function(callback,parameters) {
                console.log("function three is running independently");
               callback()
           }
       }, function(err, results) {
           callback(err, results)
       });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM