gpt4 book ai didi

Node.js 可读流 _read 用法

转载 作者:搜寻专家 更新时间:2023-11-01 00:09:39 26 4
gpt4 key购买 nike

我了解如何在 Node 的新 Streams2 库中使用可写流,但我不了解如何使用可读流。

例如,围绕 dgram 模块的流包装器:​​

var dgram = require('dgram');

var thumbs = {
twiddle: function() {}
};

var defaults = {
address: '0.0.0.0',
type: 'udp4',
port: 12345,
broadcast: null,
multicast: null,
multicastTTL: 1
};

var UDPStream = function(options) {
if (!(this instanceof UDPStream))
return new UDPStream(options);

Duplex.call(this);

options = options || {};

this.address = options.address || defaults.address;
this.type = options.type || defaults.type;
this.port = options.port || defaults.port;
this.broadcast = options.broadcast || defaults.broadcast;
this.multicast = options.multicast || defaults.multicast;
this.multicastTTL = options.multicastTTL || defaults.multicastTTL;

this._socket = dgram.createSocket(this.type, setup.bind(this));
this._socket.on('message', this.push.bind(this));
};

util.inherits(UDPStream, Duplex);

var setup = function() {
if (this.multicast) {
this._socket.addMembership(this.multicast);
this._socket.setMulticastTTL(this.multicastTTL);

this.destination = this.multicast;
} else {
// default to using broadcast if multicast address is not specified.
this._socket.setBroadcast(true);

// TODO: get the default broadcast address from os.networkInterfaces() (not currently returned)
this.destination = this.broadcast || '255.255.255.255';
}
};

UDPStream.prototype._read = function(size) {
thumbs.twiddle();
};

UDPStream.prototype._write = function(chunk, encoding, callback) {
this._socket.send(chunk, 0, chunk.length, this.port, this.destination);
callback();
};

module.exports = UDPStream;

除了 _read 实现之外,一切都有意义。这简直就是在胡闹,因为我不明白我应该在那里做什么。当 udp 套接字发出新消息时,我的数据被推送,但我无法暂停或恢复底层资源。这应该是什么样的?

最佳答案

_read 是暂停恢复机制的一部分。来自 NodeJS API 文档

When data is available, put it into the read queue by calling readable.push(chunk). If push returns false, then you should stop reading. When _read is called again, you should start pushing more data.

因此,在您的 _write 函数中,如果 socket.send 调用因返回 false 或调用带有错误的回调而失败,您应该暂停流。 _read 然后可以简单地做 this._paused = false

可能看起来像这样。

UDPStream.prototype._read = function() {
this._paused = false;
}

UDPStream.prototype._write = function(chunk, encoding, callback) {
if(!this._paused)
this._socket.send(chunk, 0, chunk.length, this.port, this.destination);
};

关于Node.js 可读流 _read 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17600705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com