我正在尝试使用 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 缓冲区的大小?
UPD:
代码:
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
作为函数的 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/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |