Node.js 中的多线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15500352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multi threading in Node.js?
提问by Bitsian
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.
我正在 node.js 中为 Windows Azure 项目实现 socket.io。我必须定期向所有连接的客户端发送数据。
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?
我是 node.js 的新手,但我想多线程是不可能的。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. And also if the client sends any data to "clientData" event, then I should be able to receive the data and process it.
本质上,我希望 requestQueue 方法像线程一样连续运行,它将以特定的时间间隔向连接的客户端发送数据。而且如果客户端向“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);
}
采纳答案by Justin Ethier
As others have suggested, you can achieve this by using the setIntervalor setTimeoutfunctions 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.
正如其他人所建议的那样,您可以通过使用setInterval或setTimeout函数定期向连接的客户端发送数据来实现这一点。尽管一切都在同一个控制线程中运行,但所有 I/O 都是异步完成的,因此您的应用程序仍然可以响应。IE,定时器运行时接收到的任何数据都会在定时器函数返回后进行排队和处理。
See Timersin the node.js manual for more information.
有关更多信息,请参阅node.js 手册中的计时器。
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.
附带说明一下,您需要让您的 node.js 应用程序专注于近乎实时地处理异步 I/O,因为这是 node.js 的优势。如果您需要进行任何繁重的计算,那么您将希望通过简单地对结果发出异步请求,以某种方式将其卸载到另一个线程/进程。
回答by ExxKA
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.
如果您查看 socket.io 首页上的示例,您将看到它们如何使用事件来开始处理流。on(eventName, function) 方法是你在 NodeJS 中监听事件的方式。
If you wish to do something based on timing (generally a bad idea), take a look at the setIntervalmethod.
如果您希望根据时间做一些事情(通常是个坏主意),请查看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>
回答by Shawn Vincent
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 APIfor 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 的单线程哲学不符,但如果您需要它,它就在那里。
回答by Shashwat Gupta
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)
});
回答by Nuray Altin
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!
您在 setInterval 等中定义的逻辑不会在单独的线程中工作并最终阻塞主线程。假设有 1000 个用户并且您调用 setTimeout 等 1000 次,最终他们将运行并花费宝贵的时间。只有最后的 IO 操作是非阻塞的!
You may consider investigating nodeJXfor multithreading in node.js
您可以考虑在 node.js 中研究用于多线程的nodeJX

