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

pim*_*vdb 2 sockets stdin node.js

我在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)
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*sch 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);
Run Code Online (Sandbox Code Playgroud)