【问题标题】:NodeJS server can't handle multiple usersNodeJS 服务器无法处理多个用户
【发布时间】:2016-05-20 07:26:40
【问题描述】:

我有一个在 Heroku(免费版)上运行的 NodeJS 服务器。服务器接受来自客户端的 HTTP POST(传递参数)并在无头浏览器中执行 Web 请求(使用参数)。无头浏览器称为HorsemanJS。 “Horseman 是一个 Node.js 模块,它使使用 PhantomJS 成为一种乐趣。它具有直接的可链接 API、可理解的控制流、支持多个选项卡和内置 jQuery。”

当我从客户端(我的计算机)向服务器发送请求(实际上是 for 20 个请求的循环)时,服务器代码正常工作(执行 20 个 HorsemanJS Web 请求),并返回预期值。然后,它等待下一个连接。这一切都很好。

问题是,当我尝试同时使用两个不同的客户端(我的电脑和手机)连接到服务器时,它会崩溃。我可以重新启动服务器并成功返回使用一个客户端。我怎样才能让它处理多个客户?

崩溃时出错:

child_process.js:788
child.stdout.addListener('data', function(chunk) {
             ^  
TypeError: Cannot read property 'addListener' of undefined
     at Object.exports.execFile (child_process.js:788:15)
     at exports.exec (child_process.js:649:18)
     at Socket.<anonymous> (/app/node_modules/node-horseman/node_modules/node-phantom-simple/node-phantom-simple.js:237:7)
     at Socket.g (events.js:199:16)
     at Socket.emit (events.js:107:17)
     at readableAddChunk (_stream_readable.js:163:16)
     at Socket.Readable.push (_stream_readable.js:126:10)
     at Pipe.onread (net.js:538:20)

从我的服务器代码中提取:

var express = require('express');
var app = express();
var Horseman = require('node-horseman'); 

app.set('port', (process.env.PORT || 5000));

var printMessage = function() { console.log("Node app running on " + app.get('port')); };

var getAbc = function(response, input)
{
    var horseman = new Horseman();

    horseman
        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0")  // building web browser
        .open('http://www.stackoverflow.com')                        
        .html()                                     
        .then(function (result) {
            var toReturn = ijk(result));

            response.writeHead(200, {'Content-Type': 'text/plain'});
            response.end(toReturn);
        }).close();
}

var handleXyz = function(request, response)
{
    getAbc(response, request.query.input); 
}

app.listen(app.get('port'), printMessage); 
app.post('/xyz', handleXyz); 

我尝试将.close 移动到.then 内部,以及.then 之前。该代码仍然适用于单个客户端,但不能用于多个客户端。

我怀疑问题是一个客户端在客户端尝试使用它时/之前关闭了一个 PhantomJS 实例。

【问题讨论】:

标签: javascript node.js heroku phantomjs headless-browser


【解决方案1】:

将 horseman.close() 放在 finally 中可能没有足够的时间来完全关闭我们的 phantomJS 进程。试着把 finally 改成 .then(),然后返回 horseman.close()。

【讨论】:

  • 试过这个。它适用于单个客户端,但适用于多个客户端。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 1970-01-01
  • 2015-05-23
  • 2015-02-24
相关资源
最近更新 更多