gpt4 book ai didi

ios - NSInputStream 缓冲区的大小

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:49 24 4
gpt4 key购买 nike

我正在尝试使用 NSInputStream 通过 TCP 套接字连接接收数据。在服务器端,我先发送数据大小,然后再发送数据本身。在 iOS 客户端,我需要从 NSInputStream 中提取前 4 个字节,因为我需要检查数据大小是否已完全接收,但我遇到了问题:

...
case NSStreamEvent.HasBytesAvailable:
if ( aStream == inputstream){
while (inputstream.hasBytesAvailable){
var readBufferRef = UnsafeMutablePointer<UnsafeMutablePointer<UInt8>>()
var readBufferLengthRef = 0
let readBufferIsAvailable = inputstream.getBuffer(readBufferRef, length: &readBufferLengthRef)
...
}
}
break

收到数据后readBufferLengthRef总是等于0。

怎么可能?

如何获取 NSInputStream 缓冲区的大小?

更新:

代码:

case NSStreamEvent.HasBytesAvailable:
NSLog("HasBytesAvaible")
var buffer = [UInt8](count: 1024, repeatedValue: 0)
if ( aStream == inputstream){

while (inputstream.hasBytesAvailable){

var readBufferRef: UnsafeMutablePointer<UInt8> = nil
var readBufferLengthRef = 0
let readBufferIsAvailable = inputstream.getBuffer(&readBufferRef, length: &readBufferLengthRef)
//debugger: readBufferLengthRef = (int)0
}
}
break

最佳答案

在您的代码中,readBufferRef被定义为“指向指针的指针”但从未分配过,因此它是 NULL 指针。

你应该做的是传递一个地址 UnsafeMutablePointer<UInt8>作为函数的 inout 参数(假设 Swift 2):

var readBufferRef: UnsafeMutablePointer<UInt8> = nil
var readBufferLengthRef = 0
let readBufferIsAvailable = inputStream.getBuffer(&readBufferRef, length: &readBufferLengthRef)

返回时,readBufferRef设置为流的读取缓冲区(直到下一次读取操作有效),并且 readBufferLengthRef包含可用字节数。

关于ios - NSInputStream 缓冲区的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40045665/

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