NSInputStream缓冲区的大小

时间:2016-10-14 14:29:41

标签: ios swift xcode

我尝试使用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

1 个答案:

答案 0 :(得分:0)

在您的代码中,{ "data": [ { "name": "Network", "description": "some description of category here.", "users": { "data": [ { "id": 1, "username": "jborne", "firstname": "Jason", "lastname": "Borne", "title": "Department Head", "company": "Borne Inc", "email": "jason@somedomain.com", "display_name": "Jason Borne", "mobile": "555-5555", "active": true, "role": "IM", } ] } } ] } 被定义为“指向指针的指针” 但从未分配过,因此它是NULL指针。

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

null

返回时,readBufferRef设置为流的读缓冲区(有效到下次读取操作),UnsafeMutablePointer<UInt8>包含 可用字节数。