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

时间:2016-07-11 07:37:28

标签: ios swift stream bonjour swift3

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

Sample

Git URL

我目前可以做的是:

  1. 发布服务并进行扫描。
  2. 在两个设备或模拟器之间创建一个I / O流套接字。
  3. 连接套接字后,我遇到了向服务发送文本的问题。

    @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.")
        }
    

    }

1 个答案:

答案 0 :(得分:3)

假设您知道sendMessage(_:)方法正在被调用,而您要做的就是检查写入是否成功,这可以通过查看返回值以直接的方式完成写方法(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)")
    }
}