使用 OutputStream 写入时如何检查是否成功?

How to check for success when writing with OutputStream?

我正在尝试编写有关 Bonjour 服务和简单​​套接字 I/O 流的示例。

Sample

Git URL

我目前能做的是:

  1. 发布一个服务,然后扫描它。
  2. 在两个设备或模拟器之间创建一个 I/O 流套接字。

套接字连接后,向服务发送文本时出现问题。

@IBAction func sendMessage(sender:AnyObject!){

        if  (self.outputStream == nil){
            print("Connection not create yet ! =====> Return")
            return
        }

        let s : String = (self.textfield?.text)!

        print("\(self.outputStream) ==> Pass Data : \(s)")

        let data: NSData = s.data(using: String.Encoding.utf8)!

        self.outputStream?.open()
        self.outputStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
        self.outputStream?.close()
        //Service no any response or log
    }

按下按钮时,似乎没有任何反应,我想知道它是否写入。

更新

客户端接收信息时出现问题。需要 运行 循环。

func netService(_ sender: NetService, didAcceptConnectionWith inputStream: InputStream, outputStream: NSOutputStream) {

            self.receiveTextView?.text = "Accept Connection Success"

            print("netService : \(sender) didAcceptConnectionWith Input Stream : \(inputStream) , Output Stream : \(outputStream)")
            inputStream.delegate = self
            outputStream.delegate = self
            inputStream.schedule(in: RunLoop.main(), forMode: RunLoopMode.defaultRunLoopMode)
            outputStream.schedule(in: RunLoop.main(), forMode: RunLoopMode.defaultRunLoopMode)
            inputStream.open()
            outputStream.open()
        }

然后在 Stream 委托中接收数据。

func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
   case Stream.Event.hasBytesAvailable:

            NSLog("HasBytesAvailable")

            var buffer = [UInt8](repeating:0, count:4096)

            let inputStream = aStream as? InputStream

            while ((inputStream?.hasBytesAvailable) != false){
                let len = inputStream?.read(&buffer, maxLength: buffer.count)
                if(len > 0){
                    let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
                    if (output != ""){
                        NSLog("Server Received : %@", output!)
                        self.receiveTextView?.text = output as String?
                    }
                }else{
                    break
                }
            }
            break
    default:
            NSLog("unknown.")
    }

}

假设您知道正在调用 sendMessage(_:) 方法,并且您要做的就是检查写入是否成功,这可以直接通过查看return 写入方法的值 (documentation) 这是一个简单的例子。

@IBAction func sendMessage(sender: AnyObject!) {
    guard let outputStream = outputStream else {
        print("Connection not create yet ! =====> Return")
        return
    }

    guard let text = textfield?.text,
        data: NSData = text.data(using: String.Encoding.utf8) else {
            print("no data")
            return
    }

    print("\(outputStream) ==> Pass Data : \(text)")
    outputStream.open()
    defer {
        outputStream.close()
    } 

    let result = outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
    if result == 0 {
        print("Stream at capacity")
    } else if result == -1 {
        print("Operation failed: \(outputStream.streamError)")
    } else {
        print("The number of bytes written is \(result)")
    }
}