简体   繁体   English

Node.js中的多线程?

[英]Multi threading in Node.js?

I am implementing socket.io in node.js for a Windows Azure project. 我正在node.js中为Windows Azure项目实现socket.io。 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. 我是node.js的新手,但我想多线程是不可能的。 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? socket.io的目的是支持实时应用程序,所以有没有什么方法可以定期向所有连接的客户端发送数据,还可以同时处理客户端发送到socket.io服务器的任何数据?

EDIT: 编辑:

This is roughly my socket.io implementation 这大致是我的socket.io实现

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. 本质上,我希望requestQueue方法像线程一样连续运行,该线程将以特定间隔向连接的客户端发送数据。 And also if the client sends any data to "clientData" event, then I should be able to receive the data and process it. 而且如果客户端向“clientData”事件发送任何数据,那么我应该能够接收数据并对其进行处理。

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. 如果您查看socket.io首页上的示例,您将看到它们如何使用事件开始处理流。 The on(eventName, function) method is how you listen for an event in NodeJS. on(eventName,function)方法是您在NodeJS中监听事件的方式。

If you wish to do something based on timing (generally a bad idea), take a look at the setInterval method. 如果你想根据时间做一些事情(通常是一个坏主意),请看一下setInterval方法。

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. 正如其他人所建议的那样,您可以通过使用setIntervalsetTimeout函数定期向连接的客户端发送数据来实现此目的。 Although everything runs within the same controlling thread, all of the I/O is done asynchronously so your application will still be responsive. 虽然一切都在同一个控制线程中运行,但所有I / O都是异步完成的,因此您的应用程序仍然会响应。 IE, any data received while the timer is running will be queued up and processed after the timer function returns. IE,计时器运行时收到的任何数据将在计时器功能返回后排队并处理。

See Timers in the node.js manual for more information. 有关更多信息,请参阅node.js手册中的Timers


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. 另外,您需要让node.js应用程序专注于近乎实时地处理异步I / O,因为这是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 还有一个用于执行线程的Node.js库:node-webworker-threads

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

This basically implements the Web Worker browser API for node.js. 这基本上实现了node.js的Web Worker浏览器API

Note that this does not align with node.js's philosophy of single threadedness, but it's there if you need it. 请注意,这与node.js的单线程理念不一致,但如果您需要它,它就在那里。

The logic you define inside the setInterval etc. won't be working in a separate thread and eventually blocking the main. 您在setInterval等中定义的逻辑将不会在单独的线程中工作并最终阻塞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. 假设有1000个用户,你调用了setTimeout等1000次,最终他们将运行并花费宝贵的时间。 Only the final IO operations are none-blocking! 只有最终的IO操作才是无阻塞的!

You may consider investigating nodeJX for multithreading in node.js 您可以考虑在node.js中调查nodeJX以进行多线程处理

Multi threading in Node.js? 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 是..在nodejs中可以使用npm模块'java4node',它这个包的方法是.multiThreading(tasks,callbacks)这个函数用于以java脚本方式执行多线程

for using this module link: https://www.npmjs.com/package/java4node 使用此模块链接: https//www.npmjs.com/package/java4node

run commend 运行表扬

npm install java4node npm安装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)
       });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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