NSInputStream缓冲区的大小 [英] Size of the NSInputStream buffer
问题描述
我正在尝试使用NSInputStream来使用TCP套接字连接接收数据。在服务器端,我在发送数据本身之前发送数据大小。在iOS客户端,我需要从NSInputStream中提取前4个字节,因为我需要检查数据的大小是否已经完全接收,但是我遇到了问题:
I'm trying to use NSInputStream for receiving data using TCP socket connection. On the server side I send data size before sending of the data itself. on the iOS client side I need to extract first 4 bytes from the NSInputStream, because I need to check if size of data has received completely, but I have a problem with it:
...
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 。
After receiving of data readBufferLengthRef always equals to 0.
怎么样?
我如何获得NSInputStream缓冲区的大小?
And how can I get size of the NSInputStream buffer?
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
推荐答案
In你的代码 readBufferRef
被定义为指针指针
但从未分配,因此它是NULL指针。
In your code, readBufferRef
is defined as a "pointer to a pointer"
but never allocated, and therefore it is the NULL pointer.
你应该做的是传递
UnsafeMutablePointer< UInt8>
的地址作为inout函数
的参数(假设Swift 2):
What you should do is to pass the address of an
UnsafeMutablePointer<UInt8>
as an inout argument to the function
(assuming Swift 2):
var readBufferRef: UnsafeMutablePointer<UInt8> = nil
var readBufferLengthRef = 0
let readBufferIsAvailable = inputStream.getBuffer(&readBufferRef, length: &readBufferLengthRef)
返回时, readBufferRef
设置为流的读缓冲区(有效到下一次读取操作),并且 readBufferLengthRef
包含
可用字节数。
On return, readBufferRef
is set to the read buffer of the stream (valid until the next read operation), and readBufferLengthRef
contains
the number of available bytes.
这篇关于NSInputStream缓冲区的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!