[英]How to create a Node.js stream server
I am trying to create a server that sends out a stream of events. 我正在尝试创建一个发送事件流的服务器。 I have created a Readable stream that I am trying to push to in response to key presses, so that I can control the stream of events to go out to the client.
我创建了一个Readable流,尝试将其推送到响应按键的响应,以便我可以控制事件流发送给客户端。
var Readable = require('stream').Readable
var rs = new Readable()
var server = http.createServer(function(req, res) {
rs.pipe(res)
})
server.listen(8888)
keypress(process.stdin)
process.stdin.on('keypress', function (ch, key) {
if( key && key.name === 'up' ) {
rs.push('up key')
}
}
When I press the up key, I get this: 当我按向上键时,得到以下信息:
events.js:85
throw er; // Unhandled 'error' event
^ Error: not implemented
at Readable._read (_stream_readable.js:464:22)
at Readable.read (_stream_readable.js:341:10)
at maybeReadMore_ (_stream_readable.js:449:12)
at _stream_readable.js:439:7
at process._tickCallback (node.js:355:11)
I don't even know what events.js is. 我什至不知道什么是events.js。 It is not my code.
这不是我的代码。
What I would hope to happen is that the string up key
would be emitted out the server stream. 我希望发生的是,字符串
up key
将从服务器流中发出。 What am I doing wrong? 我究竟做错了什么?
It turns out that what I really wanted was a chunked response, which does not pre-declare the Content-Length of the response. 事实证明,我真正想要的是分块的响应,它没有预先声明响应的Content-Length。 This allows the node server to keep the connection open, writing to it periodically.
这允许节点服务器保持连接打开,并定期对其进行写入。
var streamResponse
var server = http.createServer(function(req, response) {
response.setHeader('Content-Type', 'text/html; charset=UTF-8');
response.setHeader('Transfer-Encoding', 'chunked');
streamResponse = response
})
server.listen(44445)
setTimeout(function(){
streamResponse.write('this is a chunk');
}, 5000)
I believe that Node uses chunked transfer by default, but the key piece is calling response.write() rather than response.send(). 我相信默认情况下,Node使用分块传输,但是关键是调用response.write()而不是response.send()。 You can call response.end() when there is nothing more to send.
当没有其他要发送的信息时,可以调用response.end()。
Note: I may have some confusion in here between what is Node vs what is Express. 注意:在这里,我可能对Node和Express之间有些困惑。 If you run into any problems, that may be a place to start.
如果遇到任何问题,可能是一个开始的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.