我正在尝试使用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)"
}


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


  错误发生:可选(“错误域= NSPOSIXErrorDomain代码= 32
  \“断管\”“)


我尝试搜索了很长时间,但是找不到解决方案。任何帮助将非常感激。

最佳答案

看起来在流完成之后,不应重新使用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的实例。

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

关于ios - 使用NSOutputstream和NSInputstream写入和读取每个间隔,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37724779/

10-08 20:32