Node.js端口同时监听和读取stdin

时间:2011-05-19 18:20:30

标签: sockets node.js stdin

我在Node.js中有一个套接字服务器,我希望能够在服务器监听的同时从stdin读取。它只能部分工作。我正在使用此代码:

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键之间的时间内,监听代码似乎被暂停。

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

2 个答案:

答案 0 :(得分:6)

我刚刚编写了一个快速测试,同时处理来自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 :(得分:1)

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

尝试将过程作为node myprocess.js &

运行

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

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

相关问题