Node.js 端口同时监听和读取 stdin [英] Node.js port listening and reading from stdin at the same time

查看:23
本文介绍了Node.js 端口同时监听和读取 stdin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a socket server in Node.js and I'd like to be able to read from stdin at the same time the server is listening. It works only partially. I'm using this code:

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 之间的时间里,监听代码似乎被暂停了.

When I don't type anything, the server responds to messages of the clients, but when I start typing something, it isn't until I press Enter that it continues with this task. In the time between starting to type something and pressing Enter, the listening code seems to be suspended.

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

How can I make the server still respond to clients while I'm typing in stdin?

推荐答案

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

I just wrote a quick test and had no problems processing input from stdin and http server requests at the same time, so you'll need to provide detailed example code before I can help you. Here's the test code which runs under node 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);

这篇关于Node.js 端口同时监听和读取 stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆