如何在swift中显式读取NSInputStream中的数据?

时间:2015-05-04 13:22:02

标签: sockets swift nsstream nsinputstream nsoutputstream

我在我的应用程序中使用套接字连接。

这是我的SocketConnection.swift

    init(host: String, port:UInt32){
        self.host = host
        self.port = port
        self.status = false
        output = ""
        super.init()
    }

    func stream(aStream: NSStream, handleEvent aStreamEvent: NSStreamEvent) {
        switch aStreamEvent {

        case NSStreamEvent.OpenCompleted:
            break

        case NSStreamEvent.HasBytesAvailable:

            break

        case NSStreamEvent.HasSpaceAvailable:
            break

        case NSStreamEvent.EndEncountered:

//            aStream.close()
            aStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
            break

        case NSStreamEvent.None:

            break

        case NSStreamEvent.ErrorOccurred:

            break

        default:
            println("# something weird happend")
            break
        }
    }

    func connect() {
        println("# connecting to \(host):\(port)")
        var cfReadStream : Unmanaged<CFReadStream>?
        var cfWriteStream : Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &cfReadStream, &cfWriteStream)
        inputStream = cfReadStream!.takeRetainedValue()
        outputStream = cfWriteStream!.takeRetainedValue()

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

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

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


    func read(){  
        var buffer = [UInt8](count: bufferSize, repeatedValue: 0)
        output = ""
        while (self.inputStream!.hasBytesAvailable){
            var bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)
            if bytesRead >= 0 {
                output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding: encoding)! as String
            } else {
                println("# error")
            }
            println("> \(output)")
        }
    }

    func send(message:String){        
            let data:NSData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
            let bytesWritten = self.outputStream!.write(UnsafePointer(data.bytes), maxLength: data.length)
            println("< send to \(host)")

    }

在我的ViewController.swift中, 我正在连接到这样的服务器

var socketConnection = SocketConnection(host: _ip, port: _port) 
socketConnection.connect() 
socketConnection.send(urlString) 
socketConnection.read()

现在我可以通过套接字发送我的url字符串,但是当我明确地阅读时,如果我从NSStreamEvent.HasBytesAvailable调用相同的读取函数打印服务器响应,我没有从服务器获取数据。但是如何触发事件队列?

我想明确地调用此socketConnection.read() ..我该怎么做?

连接2秒后,它会关闭连接通道,我想保持连接直到我关闭。

帮助我摆脱这个问题。

由于

2 个答案:

答案 0 :(得分:1)

如下更改您的read(),然后调用read()函数,以防NSStreamEvent.HasBytesAvailable:

private func read(stream: InputStream) {
    let maxReadLength = 1024
    let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: maxReadLength)
    while stream.hasBytesAvailable {
        let numberOfBytesRead = inputStream?.read(buffer, maxLength: maxReadLength)

        if numberOfBytesRead! < 0 {
            if let _ = inputStream?.streamError {
                break
            }
        }

        if let message = processedMessageString(buffer: buffer, length: numberOfBytesRead!) {
            delegate?.receivedMessage(message: message)
        }
    }
}

答案 1 :(得分:0)

您不需要显式调用读取功能。如下更改您的读取函数,以防万一Stream.Event.hasBytesAvailable:。

func read(stream: InputStream) {
let maxReadLength = 1024
var buffer = [uint8](repeating: 0, count: maxReadLength)
while stream.hasBytesAvailable {
    let numberOfBytesRead : Int = stream.read(&buffer, maxLength: maxReadLength)
    if numberOfBytesRead < 0 {
        if let _ = stream.streamError {
            break
        }
    }

    if let message = processedMessageString(buffer: buffer, length: numberOfBytesRead) {
        delegate?.receivedMessage(message: message)
    }
}}

如果要显式调用read(),则需要将流作为参数传递,并在ViewController类中调用read函数-

socketConnection.read(stream)