在写入Stream之前如何等待提示?

时间:2016-01-10 22:12:09

标签: ios swift sockets nsstream

我正在尝试通过TCP连接到设备并发送命令。设备会显示提示">"什么时候它准备好了命令。如果我发送的命令太快,第二个命令将会丢失,因为设备仍在处理第一个命令。连接时,最简单的示例是在下面的代码中。 " ATZ"命令正在处理,所以" ATSP0"命令错过了。添加缓冲区或循环以等待设备在队列中发送下一个命令的最佳方法是什么?

import UIKit

class Connection: UITableViewController, NSStreamDelegate {
    @IBOutlet weak var messageView: UITextView!
    @IBOutlet weak var sendText: UITextField!
    @IBOutlet weak var ipAddress: UITextField!
    @IBOutlet weak var port: UITextField!

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

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func connectServer(sender: UIButton) {
        let host : CFString = ipAddress.text!
        let port : UInt32 = UInt32(self.port.text!)!
        var readstream : Unmanaged<CFReadStream>?
        var writestream : Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &readstream, &writestream)

        inputStream = readstream!.takeRetainedValue()
        outputStream = writestream!.takeRetainedValue()

        self.inputStream.delegate = self
        self.outputStream.delegate = self

        inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
        outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

        inputStream.open()
        outputStream.open()

        messageView.text = "\(messageView.text)Connected to " + ipAddress.text! + "\r"

        progSendMessage("ATZ")
        progSendMessage("ATSP0") //Prompt not ready and this command is lost
    }
    @IBAction func sendMessage(sender: UIButton) {
        let textToSend: String = self.sendText.text!
        if (textToSend != "")  {
            progSendMessage(textToSend)
        }
    }

    func progSendMessage(var message: String) {
        message += "\r"
        let data: NSData = message.dataUsingEncoding(NSUTF8StringEncoding)!
        outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
        self.sendText.text = ""
    }

    func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
        switch (eventCode){
        case NSStreamEvent.ErrorOccurred:
            print("ErrorOccurred")
            print(aStream.streamError?.description)
            break
        case NSStreamEvent.EndEncountered:
            print("EndEncountered")
            break
        case NSStreamEvent.None:
            print("None")
            break
        case NSStreamEvent.HasBytesAvailable:
            print("HasBytesAvaible")
            var buffer = [UInt8](count: 4096, repeatedValue: 0)
            if ( aStream == inputStream){

                while (inputStream.hasBytesAvailable){
                    let len = inputStream.read(&buffer, maxLength: buffer.count)
                    if(len > 0){
                        let output = NSString(bytes: &buffer, length: buffer.count, encoding: NSUTF8StringEncoding)
                        if (output != ""){
                            print("server said: %@", output!)
                            messageView.text = messageView.text + (output?.description)! + "\r"
                        }
                    }
                }
            }
            break
        case NSStreamEvent.OpenCompleted:
            print("OpenCompleted")
            break
        case NSStreamEvent.HasSpaceAvailable:
            print("HasSpaceAvailable")
            break
        default:
            print("Default")
            break
        }
    }
}

0 个答案:

没有答案