【问题标题】:Node.js port listening and reading from stdin at the same timeNode.js 端口同时监听和读取标准输入
【发布时间】:2011-09-05 23:02:51
【问题描述】:

我在 Node.js 中有一个套接字服务器,我希望能够在服务器正在侦听的同时从标准输入读取。它仅部分起作用。我正在使用此代码:

process.stdin.on('data', function(chunk) {
    for(var i = 0; i < streams.length; i++) {
        // code that sends the data of stdin to all clients
    }
});

// ...

// (Listening code which responds to messages from clients)

当我不输入任何内容时,服务器会响应客户端的消息,但是当我开始输入内容时,直到我按 Enter 后它才会继续执行此任务。在开始输入内容和按 Enter 之间的时间里,监听代码似乎被暂停了。

当我输入标准输入时,如何让服务器仍然响应客户端?

【问题讨论】:

    标签: sockets node.js stdin


    【解决方案1】:

    我刚刚写了一个快速测试,同时处理来自 stdin 和 http 服务器请求的输入没有问题,所以你需要提供详细的示例代码才能帮助你。这是在节点 0.4.7 下运行的测试代码:

    var util=require('util'),
        http=require('http'),
        stdin=process.stdin;
    
    // handle input from stdin
    stdin.resume(); // see http://nodejs.org/docs/v0.4.7/api/process.html#process.stdin
    stdin.on('data',function(chunk){ // called on each line of input
      var line=chunk.toString().replace(/\n/,'\\n');
      console.log('stdin:received line:'+line);
    }).on('end',function(){ // called when stdin closes (via ^D)
      console.log('stdin:closed');
    });
    
    // handle http requests
    http.createServer(function(req,res){
      console.log('server:received request');
      res.writeHead(200,{'Content-Type':'text/plain'});
      res.end('success\n');
      console.log('server:sent result');
    }).listen(20101);
    
    // send send http requests
    var millis=500; // every half second
    setInterval(function(){
      console.log('client:sending request');
      var client=http.get({host:'localhost',port:20101,path:'/'},function(res){
        var content='';
        console.log('client:received result - status('+res.statusCode+')');
        res.on('data',function(chunk){
          var str=chunk.toString().replace(/\n/,'\\n');
          console.log('client:received chunk:'+str);
          content+=str;
        });
        res.on('end',function(){
          console.log('client:received result:'+content);
          content='';
        });
      });
    },millis);
    

    【讨论】:

    • +1 表示尝试重现但未发现任何问题!我认为代码看起来不错。
    • 非常感谢,但我必须说我也可以用这个来重现我的问题。它每 0.5 秒发送一次,但是一旦我输入它就会被暂停。当我按 Enter 时,消息正在再次发送。提及我使用的是 Windows 可能会有所帮助?
    • 我用你的例子记录了我所看到的,你看到的是同样的东西吗? youtube.com/watch?v=AeRQHn0z1g8
    • 我在 Linux 下运行时没有看到同样的情况,因此很可能是 Windows 控制台阻塞了您的线程的问题。有关在 Windows 下运行 Node 相关问题的说明,请参阅stackoverflow.com/questions/6061053/…
    • @Rob Raisch:谢谢,这确实可能是问题所在。据我所知,没有解决方案。对吗?
    【解决方案2】:

    您是否使用&amp; 作为后台进程运行脚本?否则控制台是进程的控制终端,并且可能在您键入时发送SIGSTOP 消息以避免竞争条件或其他东西。

    尝试以node myprocess.js &amp; 运行进程

    如果仍然发生,请尝试nohup node myprocess.js &amp;

    http://en.wikipedia.org/wiki/Signal_(computing)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 2010-10-20
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-23
      相关资源
      最近更新 更多