SWIFT - 如何获取服务器流

时间:2017-03-31 01:26:13

标签: swift cfstream

在客户端上,我们可以使用CFStreamCreatePairWithSocketToHost来获取ReadStream和WriteStream。

服务器获得clientSocket后,我们如何获得ReadStream和WriteStreaam?

1 个答案:

答案 0 :(得分:2)

import UIKit

class Connection: NSObject, NSStreamDelegate {
    var inputStream: NSInputStream!
    var outputStream: NSOutputStream!

    func connect() {
        var readStream:  Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(nil, "193.10.1.22", 17, &readStream, &writeStream)

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

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

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

        self.inputStream.open()
        self.outputStream.open()
    }
}