简体   繁体   English

如何运行多个node.js服务器

[英]How to run multiple node.js servers

I have two Express servers running on different ports. 我有两个Express服务器在不同的端口上运行。 The first server (web server) provides a website and the second server (data server) emits data every 100 ms using socket.io. 第一个服务器(Web服务器)提供一个网站,第二个服务器(数据服务器)使用socket.io每100毫秒发送一次数据。 When I open the website in the browser the data appears as expected. 当我在浏览器中打开网站时,数据按预期显示。 But when I then open the website in a second browser, all the emitted data in the first browser slows remarkably down until the second browser is done loading the site. 但是当我在第二个浏览器中打开网站时,第一个浏览器中发出的所有数据都会显着减慢,直到第二个浏览器加载完网站。

I should probably mention that the application is running on a Raspberry Pi. 我应该提一下应用程序是在Raspberry Pi上运行的。 The website loading time is not so critical, but the data emission is. 网站加载时间不是那么关键,但数据发布是。

Is there some way to run the node.js servers so they won't be affected by the load on each other? 有没有办法运行node.js服务器,以便它们不会受到彼此负载的影响?

Right now the web server is in the main app.js file that is run by node and the data server is a module required by the web server. 现在,Web服务器位于由节点运行的主app.js文件中,数据服务器是Web服务器所需的模块。 Something like this: 像这样的东西:

app.js: app.js:

var express = require('express');
var data = require('data-server.js');

var app = express();

// Web server setup and handling (mostly Express defaults)

app.listen(3000);

module.exports = app;

data-server.js: 数据server.js:

var app = require('express')();
var server = require('http').Server(app).listen(3001)
var io = require('socket.io')(server);

// Socket.io code that emits data every 100 ms

module.exports = io;

Update 更新

Turns out it was my database query that was holding on to node so it couldn't emit because the emission function was waiting for the database to be free. 事实证明,这是我的数据库查询,它持有节点,因此它无法发出,因为发射功能正在等待数据库空闲。

You should use the same port and the same node process for both your regular HTTP traffic and your websocket traffic. 您应该对常规HTTP流量和websocket流量使用相同的端口和相同的节点进程。 It would minimise the performance impact on your raspberry pi. 它可以最大限度地降低对树莓派的性能影响。 Example : 示例:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

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

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