使用NSOutputstream和NSInputstream来写入和读取每个间隔

时间:2016-06-09 11:32:03

标签: ios swift sockets nsrunloop nsoutputstream

我正在尝试使用NSOutputstream和NSInputstream来编写和读取每个间隔,比如5秒。这是以P2P方式与Windows上的C#程序进行通信。

我想使用NSOutputstream每隔5秒向C#程序发送一个请求,然后NSInputstream将读取C#程序的响应。

目前我有:

class Connection : NSObject, NSStreamDelegate {
var serverAddress: CFString
let serverPort: UInt32 = 11000

private var inputStream: NSInputStream!
private var outputStream: NSOutputStream!

init(serverAddress: CFString) {
    self.serverAddress = serverAddress
}

func connect() {
    print("connecting...")

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

    CFStreamCreatePairWithSocketToHost(nil, self.serverAddress, self.serverPort, &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()

    print("connected...")
}

func disconnect() {
    self.inputStream.close()
    self.outputStream.close()
}

func receive() -> String {
    let data: NSData = "GiveMeCurrentTime".dataUsingEncoding(NSUTF8StringEncoding)!

    let bytesWritten = outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)

    print("wrote \(bytesWritten) bytes")

    var buffer = [UInt8](count: 100, repeatedValue: 0)
    inputStream.read(&buffer,maxLength: buffer.count)

    let currentTime = String.fromCString(UnsafePointer(buffer))
    print("Data received is \(currentTime)")


    return currentTime
}

func stream(stream: NSStream, handleEvent eventCode: NSStreamEvent) {
    //print("stream event")

    if stream === inputStream {
        switch eventCode {
        case NSStreamEvent.ErrorOccurred:
            print("input: ErrorOccurred: \(stream.streamError?.description)")
        case NSStreamEvent.OpenCompleted:
            print("input: OpenCompleted")
        case NSStreamEvent.HasBytesAvailable:
            print("input: HasBytesAvailable")
            break;
        case NSStreamEvent.HasSpaceAvailable:
            break;
        default:
            print("\(eventCode)")
            break
        }
    }
    else if stream === outputStream {
        switch eventCode {
        case NSStreamEvent.ErrorOccurred:
            print("output: ErrorOccurred: \(stream.streamError?.description)")
        case NSStreamEvent.OpenCompleted:
            print("output: OpenCompleted")
        case NSStreamEvent.HasSpaceAvailable:
            print("output: HasSpaceAvailable")
            // Here you can write() to `outputStream`
            break;
        default:
            print("\(eventCode)")
            break
        }
    }
}

连接类将在下面与NSTimer和NSRunLoop一起使用:

func start(ipAddress ipAddress: String) {
        self.conn = Connection(serverAddress: ipAddress)
        self.conn!.connect()
        self.sendTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "getTimeAndUpdateUI", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(self.sendTimer!, forMode: NSDefaultRunLoopMode)
    }
}

func getTimeAndUpdateUI() {
    let time = self.conn!.receive()
    self.timeLabel.text = "Current time is \(time)"
}

第一次运行总是没问题 - 我可以获得当前时间并正确显示。但随后的运行永远不会成功。输出流无法写出任何字节。输入流在读取时出现以下错误:

  

ErrorOccurred:可选(“错误域= NSPOSIXErrorDomain代码= 32   “破管”,“)

我尝试了很长时间但找不到解决方案。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

看起来NSInputStream和NSOutputStream不应该在流完成后重复使用。我通过将代码更改为以下来解决问题:

func start(ipAddress ipAddress: String) {
        self.conn = Connection(serverAddress: ipAddress)
        self.sendTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "getTimeAndUpdateUI", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(self.sendTimer!, forMode: NSDefaultRunLoopMode)
}

func getTimeAndUpdateUI() {
    self.conn!.connect()
    let time = self.conn!.receive()
    self.timeLabel.text = "Current time is \(time)"
    self.conn!.disconnect()
}

每次iOS轮询服务器以获取信息时,它都会重新创建NSInputStream和NSOutputStream的实例。

欢迎提出任何改进建议。感谢。