ios - 检测可以向 NSOutputStream 写入多少字节

标签 ios objective-c swift macos nsstream

我尝试实现的基本问题:

我有两个流。 NSInputStreamNSOutputStream。 现在我想从输入中获取一些数据处理它们(添加一些帧对它们进行编码等等)并传递给输出。到目前为止一切顺利。

实际问题

问题是 NSOutputStream API - write:maxLength: 可以返回实际写入的字节数。该值可以与传递的长度不同。这是一个问题,因为它需要创建额外的逻辑来维护某种缓冲区。 我想避免这种情况。我现在想知道输出流在没有缓冲的情况下将接受多少字节,以便我可以计算应该从输入流读取多少数据(我将添加一些帧和编码)。 我不想维持额外的缓冲区。

输出流与 TCP 套接字相关联,输入流可以与任何类型的资源相关联。

最佳答案

This is the apple implementation对于问题:

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
    switch(eventCode) {
        case NSStreamEventHasSpaceAvailable:
        {
            uint8_t *readBytes = (uint8_t *)[_data mutableBytes];
            readBytes += byteIndex; // instance variable to move pointer
            int data_len = [_data length];
            unsigned int len = ((data_len - byteIndex >= 1024) ?
                1024 : (data_len-byteIndex));
            uint8_t buf[len];
            (void)memcpy(buf, readBytes, len);
            len = [stream write:(const uint8_t *)buf maxLength:len];
            byteIndex += len;
            break;
        }
        // continued ...
    }
}

在此实现中,一次写入 1024 字节的 block 。

并提供了注释:

There is no firm guideline on how many bytes to write at one time. Although it may be possible to write all the data to the stream in one event, this depends on external factors, such as the behavior of the kernel and device and socket characteristics. The best approach is to use some reasonable buffer size, such as 512 bytes, one kilobyte (as in the example above), or a page size (four kilobytes).

如前所述,它取决于另一侧。不知道是否可以通过调查接收器来解决。但是,也许建议一次写入的大小可能会降低某些字节不会被写入的可能性。应该实现该逻辑。

关于ios - 检测可以向 NSOutputStream 写入多少字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35994168/

相关文章:

iOS - NSManagedObject 在不保存的情况下保持分配多长时间

objective-c - 如何在 Objective-C 的 mac 浏览器中的 safari、Chrome、Opera、Firefox 中设置主页

objective-c - MetalKit - 如何使用(MTKTextureLoader 方法)newTextureWithContentsOfURL 的选项?

Swift - 将结构传递给方法?

ios - 使用 GameKit 通过蓝牙发送数据崩溃

ios - 让按钮快速改变颜色

iOS 8 横向 : Keyboard does not display correctly

ios - 将标题添加到 CSV 文件

objective-c - Swift 中 load 方法的替代方法

ios - 快速将JSON值解析为全局数组