从Swift中的NSInputStream接收数据

前端之家收集整理的这篇文章主要介绍了从Swift中的NSInputStream接收数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试使用NSOutputStream和NSInputStream在Swift中发送和接收数据。发送数据工作正常,但是我有一些有关接收的问题。

我找到了一个处理NSStreamEvent的解决方案,我已经尝试过了。

首先我的初始化连接的功能

func initNetworkCommunication(){  
    var host : CFString = "127.0.0.1"
    var port : UInt32 = 7001
    var readstream : Unmanaged<CFReadStream>?
    var writestream : Unmanaged<CFWriteStream>?
    CFStreamCreatePairWithSocketToHost(kcfAllocatorDefault,host,port,&readstream,&writestream)

    inputstream = readstream!.takeRetainedValue()
    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()   
}

这部分工作。我已经将代理设置为self,所以我应该能够处理这个类中的NSStreamEvents。

func stream(aStream: NSStream,handleEvent eventCode: NSStreamEvent) {
    switch (eventCode){
    case NSStreamEvent.OpenCompleted:
        NSLog("Stream opened")
        break
    case NSStreamEvent.HasBytesAvailable:
        NSLog("HasBytesAvailable")
        break
    case NSStreamEvent.ErrorOccurred:
         NSLog("ErrorOccurred")
        break
    case NSStreamEvent.EndEncountered:
        NSLog("EndEncountered")
        break
    default:
        NSLog("unknown.")
    }
}

在我的理解中,每当有数据到达时,它应该打印“HasBytesAvaible”,但它打印“未知”。每次。所以我玩了一下,并与此一起工作:

func stream(aStream: NSStream,handleEvent eventCode: NSStreamEvent) {

    var buffer = [UInt8](count: 4096,repeatedValue: 0)
    while (inputstream.hasBytesAvailable){
        let result: Int = inputstream.read(&buffer,maxLength: buffer.count)
    }

    switch (eventCode){
    case NSStreamEvent.OpenCompleted:
        NSLog("Stream opened")
        break
    case NSStreamEvent.HasBytesAvailable:
        NSLog("HasBytesAvailable")
        var output = NSString(bytes: &buffer,length: buffer.count,encoding: NSUTF8StringEncoding)
        NSLog("output: %@",output)
        receiveMessage(output) //only adds the message to an array
        break
    case NSStreamEvent.ErrorOccurred:
        NSLog("ErrorOccurred")
        break
    case NSStreamEvent.EndEncountered:
          NSLog("EndEncountered")
        break
    default:
        NSLog("unknown.")
    }
}

它是这样工作的,但我想问你是否是正确的方法?这时最好的做法是什么?

UPDATE
我在几个星期前再次工作,想出了我的错误。所以这里是工作代码

func stream(aStream: NSStream,handleEvent eventCode: NSStreamEvent) {
        switch (eventCode){
    case NSStreamEvent.ErrorOccurred:
        NSLog("ErrorOccurred")
        break
    case NSStreamEvent.EndEncountered:
        NSLog("EndEncountered")
        break
    case NSStreamEvent.None:
        NSLog("None")
        break
    case NSStreamEvent.HasBytesAvailable:
        NSLog("HasBytesAvaible")
        var buffer = [UInt8](count: 4096,repeatedValue: 0)
        if ( aStream == inputstream){

            while (inputstream.hasBytesAvailable){
                var len = inputstream.read(&buffer,maxLength: buffer.count) 
                if(len > 0){
                    var output = NSString(bytes: &buffer,encoding: NSUTF8StringEncoding) 
                    if (output != ""){
                        NSLog("server said: %@",output!)
                    }
                }
            } 
        }
        break
    case NSStreamEvent.allZeros:
        NSLog("allZeros")
        break
    case NSStreamEvent.OpenCompleted:
        NSLog("OpenCompleted")
        break
    case NSStreamEvent.HasSpaceAvailable:
        NSLog("HasSpaceAvailable")
        break
  }
你错过了hasSpaceAvailable的事件,我预计这个事件会发生在“unknown”时。它告诉你,它已经准备好接收更多的数据。

通常,我避免在switch语句中使用默认的枚举,因为编译器会告诉你什么时候错过了什么。

猜你在找的Swift相关文章