nodejs http response.write:可能是内存不足吗?

如果我有以下代码每10毫秒发送一次数据到客户端:

setInterval(function() { res.write(somedata); }, 10ms); 

如果客户端收到数据的速度很慢,会发生什么?

请问服务器出现内存不足的错误?

编辑:实际上连接保持活着,服务器无休止地发送jpeg数据(HTTP多部分/ x混合replace标题+正文+标题+正文…..)
由于node.js response.write是asynchronous的,
所以一些用户猜测它可能会在内部缓冲区中存储数据,并等到低层告诉它可以发送,
所以内部缓冲区会增长,对吗?

如果我是对的,那么如何解决呢?
问题是node.js没有通知我什么时候发送一个写入数据。

换句话说,我不能以这种方式告诉用户在理论上没有“内存不足”的风险,以及如何解决这个问题。

更新:通过user568109给出的关键字“drain”事件,我研究了node.js的来源,得出结论:
这真的会造成“内存不足”的错误。 我应该检查response.write(…)=== false的返回值,然后处理响应的“漏”事件。

http.js:

 OutgoingMessage.prototype._buffer = function(data, encoding) { this.output.push(data); //-------------No check here, will cause "out-of-memory" this.outputEncodings.push(encoding); return false; }; OutgoingMessage.prototype._writeRaw = function(data, encoding) { //this will be called by resonse.write if (data.length === 0) { return true; } if (this.connection && this.connection._httpMessage === this && this.connection.writable && !this.connection.destroyed) { // There might be pending data in the this.output buffer. while (this.output.length) { if (!this.connection.writable) { //when not ready to send this._buffer(data, encoding); //----------> save data into internal buffer return false; } var c = this.output.shift(); var e = this.outputEncodings.shift(); this.connection.write(c, e); } // Directly write to socket. return this.connection.write(data, encoding); } else if (this.connection && this.connection.destroyed) { // The socket was destroyed. If we're still trying to write to it, // then we haven't gotten the 'close' event yet. return false; } else { // buffer, as long as we're not destroyed. this._buffer(data, encoding); return false; } }; 

一些陷阱:

  1. 如果通过HTTP发送它不是一个好主意。 如果在指定的时间内未完成请求,浏览器可能会将该请求视为超时。 服务器也将closures空闲时间过长的连接。 如果客户端跟不上,超时几乎是确定的。

  2. 10ms的setInterval也受到一些限制。 这并不意味着它会在每10ms后重复,10ms是重复之前等待的最小时间。 它会比你设定的时间间隔慢。

  3. 假设您有机会使用数据重载响应,那么在某个时间点,服务器将结束连接,并根据设置的限制响应“ 413 Request Entity Too Large

  4. Node.js具有单线程体系结构,最大内存限制为1.7 GB左右。 如果您上面的服务器限制设置得太高,并有许多传入连接,则会process out of memory不足错误。

因此,如果有适当的限制,它可能会超时或请求太大。 (在你的程序中没有其他错误。)

更新

你需要使用drain事件。 http响应是可写的stream。 它有自己的内部缓冲区。 当缓冲区被清空时,会触发漏极事件。 你应该更深入地了解更多关于溪stream的知识。 这将帮助你不只在http。 你可以在网上find关于stream的几个资源。