坚持使用hasSpaceAvailable并且无法从NSInputStream中读取

时间:2016-08-10 20:28:04

标签: swift macos tcp network-programming nsstream

我在处理流事件时遇到了问题。我有一个客户端应用程序,它通过TCP连接到服务器,并不断从服务器接收JSON数据。

到目前为止,我创建了这样的流:

// Create Stream

var readStream : Unmanaged<CFReadStream>?
var writeStream : Unmanaged<CFWriteStream>?

let host : CFString = NSString(string: serverUrl!)
let port : UInt32 = UInt32(serverPort)

CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &readStream, &writeStream)

inputStream = readStream!.takeUnretainedValue()
outputStream = writeStream!.takeRetainedValue()

inputStream!.delegate = self
outputStream!.delegate = self

inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

inputStream!.open()
outputStream!.open()

// Send Authentication Data

let uid = 1000000000 + arc4random() % 2000000000
let joinRoomMsg : NSData = "{\"roomid\": \(realRoomID!), \"uid\": \(uid)}".dataUsingEncoding(NSUTF8StringEncoding)!

sendSocketData(outputStream!, totalLength: joinRoomMsg.length + 16, headerLength: 16, protocolVersion: 1, action: 7, param5: 1, data: joinRoomMsg)

这里是sendSocketData func:

func sendSocketData(outputStream: NSOutputStream, totalLength: Int32, headerLength: CShort, protocolVersion: CShort, action: Int32, param5: Int32, data: NSData?) {

    var totalLengthBE = totalLength.bigEndian
    var headerLengthBE = headerLength.bigEndian
    var protocolVersionBE = protocolVersion.bigEndian
    var actionBE = action.bigEndian
    var param5BE = param5.bigEndian

    withUnsafePointers(&totalLengthBE, &headerLengthBE, &protocolVersionBE) {
        outputStream.write(UnsafePointer($0), maxLength: sizeofValue(totalLengthBE))
        outputStream.write(UnsafePointer($1), maxLength: sizeofValue(headerLengthBE))
        outputStream.write(UnsafePointer($2), maxLength: sizeofValue(protocolVersionBE))
    }

    withUnsafePointers(&actionBE, &param5BE) {
        outputStream.write(UnsafePointer($0), maxLength: sizeofValue(actionBE))
        outputStream.write(UnsafePointer($1), maxLength: sizeofValue(param5BE))
    }

    if data != nil {
        outputStream.write(UnsafePointer(data!.bytes), maxLength: data!.length)
    }
}

处理:

func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
    if aStream === inputStream {
        switch eventCode {
        case NSStreamEvent.ErrorOccurred:
            print("iStream ErrorOccurred")
        case NSStreamEvent.EndEncountered:
            print("iStream EndEncountered")
        case NSStreamEvent.OpenCompleted:
            print("iStream Opened")
        case NSStreamEvent.HasBytesAvailable:
            print("Stream HasBytesAvailable")
            // read data here...
        default:
            print("iStream Unknow")
        }
    } else if aStream === outputStream {
        switch eventCode {
        case NSStreamEvent.OpenCompleted:
            print("oStream Opened")
        case NSStreamEvent.ErrorOccurred:
            print("oStream ErrorOccurred")
        case NSStreamEvent.HasSpaceAvailable:
            print("oStream HasSpaceAvailable")
        default:
            print("oStream Unknow")
        }
    }
}

服务器确实向我发送了JSON数据。

Screenshot

现在我应该能够使用eventCode NSStreamEvent.HasBytesAvailable从inputStream中读取数据。

但问题是:流事件处理程序向我发送NSStreamEvent.HsaSpaceAvailable并在此处停留。 inputStream.hasBytesAvailable返回false,我无法阅读任何内容。

根据Stream Programing Guide

  

如果委托收到NSStreamEvent.HasSpaceAvailable事件并且没有向流写入任何内容,则在NSOutputStream对象接收到更多字节之前,它不会从运行循环接收更多空间可用事件。发生这种情况时,将重新启动运行循环以获取空间可用事件。

但是我已经没有数据要写入流了。

我确实试着给它写一些随机数据,但没有运气。 我还尝试在outputStream.hasSpaceAvailable返回true后发送身份验证数据,但它也没有做任何事情。

我的代码有问题吗?

1 个答案:

答案 0 :(得分:0)

我终于意识到,仅由于此函数的签名不正确/已过时,stream()函数不起作用。

这是您正在使用的:

func stream(aStream: Stream, handleEvent eventCode: Stream.Event)

但实际上应该是:

func stream(_ aStream: Stream, handle eventCode: Stream.Event)