简体   繁体   English

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

[英]Use NSOutputstream and NSInputstream to write and read every interval

I'm trying to use NSOutputstream and NSInputstream to write and read every interval, say 5 seconds. 我正在尝试使用NSOutputstream和NSInputstream写入和读取每个间隔(例如5秒)。 This is to communicate with a C# program on windows in P2P fashion. 这是为了以P2P方式与Windows上的C#程序进行通信。

I want to use NSOutputstream to send the C# program a request every 5 seconds and then NSInputstream will read the response from the C# program. 我想使用NSOutputstream每5秒向C#程序发送一个请求,然后NSInputstream将从C#程序读取响应。

Currently I have: 目前我有:

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
        }
    }
}

The connection class will be used as below with NSTimer and NSRunLoop: 该连接类将与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)"
}

The first run is always okay - I can get the current time and display it correctly. 第一次运行总是可以的-我可以获取当前时间并正确显示它。 But the subsequent runs never succeed. 但是随后的运行永远不会成功。 The output stream cannot write any byte out. 输出流不能写出任何字节。 And the input stream got the following error when reading: 并且读取时输入流出现以下错误:

ErrorOccurred: Optional("Error Domain=NSPOSIXErrorDomain Code=32 \\"Broken pipe\\"") 错误发生:可选(“错误域= NSPOSIXErrorDomain代码= 32 \\“断管\\”“)

I've tried searching for a long time but couldn't find a solution. 我尝试搜索了很长时间,但是找不到解决方案。 Any help would be much appreciated. 任何帮助将非常感激。

Looks like NSInputStream and NSOutputStream are not supposed to be re-used after a stream finishes. 看起来在流完成之后,不应重新使用NSInputStream和NSOutputStream。 I fix the problem by changing the code to below: 我通过将代码更改为以下来解决此问题:

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()
}

Every time iOS poll the server for information, it recreates an instance of NSInputStream and NSOutputStream. 每次iOS轮询服务器以获取信息时,它都会重新创建NSInputStream和NSOutputStream的实例。

Any suggestion to improve is welcome. 欢迎提出任何改进建议。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用NSInputStream和NSOutputStream读取和写入音频文件 - How to read and write audio file using NSInputStream and NSOutputStream 如何在将其写入iOS中的NSOutputStream时读取NSInputStream? - How do I read an NSInputStream while writing it to an NSOutputStream in iOS? 关闭NSOutputstream和NSInputstream - Closing an NSOutputstream & NSInputstream NSInputStream和NSOutputStream问题 - NSInputStream and NSOutputStream problems 我可以使用NSStream,NSInputStream和NSOutputStream从C#应用程序发送和接收数据吗? - Can I use NSStream, NSInputStream, and NSOutputStream to send and receive data from a C# application? 通过NSInputStream / NSOutputStream传输多个图像 - Transfer Multiple Images via NSInputStream/NSOutputStream iOS:NSInputStream / NSOutputStream - CFNetwork SSLHandshake失败(-9806) - iOS : NSInputStream / NSOutputStream - CFNetwork SSLHandshake failed (-9806) Mac Chat App,未获取NSInputStream和NSOutputStream - Mac Chat App, Not getting NSInputStream & NSOutputStream 如何在Objective-c中将数据从NSOutputStream传递到NSInputStream - how to pipe data from NSOutputStream to NSInputStream in objective-c 如何在流打开后将NSStream(NSInputStream / NSOutputStream)转换为SSL? - How to convert NSStream (NSInputStream / NSOutputStream) to SSL after stream opened?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM