未调用“ hasBytesAvailable”

时间:2018-09-06 13:09:52

标签: ios macos sockets

我能够写入套接字,但不能读取服务器的输出。我的服务器正在接受输入并将其转换为大写并提供输出。我无法获得输出。

我尝试在Google中搜索,但未找到解决方案。我尝试不关闭连接但没有运气。

class ViewController: NSViewController , StreamDelegate{

@IBOutlet weak var txtMessage: NSTextField!
@IBOutlet weak var lblOutput: NSTextField!

var inputStream: InputStream?
var outputStream: OutputStream?
var readStream : Unmanaged<CFReadStream>?
var writeStream : Unmanaged<CFWriteStream>?

override func viewDidLoad() {
    super.viewDidLoad()
    setupConnection()
    // Do any additional setup after loading the view.
}

override func viewWillAppear() {

}

override var representedObject: Any? {
    didSet {
    // Update the view, if already loaded.
    }
}

@IBAction func btnSendMsg(_ sender: NSButton) {
    let strData = txtMessage.stringValue
    send(message: strData)

}

func setupConnection(){
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, "localhost" as CFString, 6688, &readStream, &writeStream)
    open()
}

func open(){
    print("Opening streams.")
    inputStream = readStream?.takeRetainedValue()
    outputStream = writeStream?.takeRetainedValue()
    outputStream?.delegate = self
    inputStream?.delegate = self
    outputStream?.schedule(in: .current, forMode: .defaultRunLoopMode)
    inputStream?.schedule(in: .current, forMode: .defaultRunLoopMode)
    outputStream?.open()
    inputStream?.open()
}

func close() {
    print("Closing streams.")
    inputStream?.close()
    outputStream?.close()
    inputStream?.remove(from: .current, forMode: .defaultRunLoopMode)
    outputStream?.remove(from: .current, forMode: .defaultRunLoopMode)
    inputStream?.delegate = nil
    outputStream?.delegate = nil
    inputStream = nil
    outputStream = nil
}

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

    switch eventCode {
    case Stream.Event.hasBytesAvailable:
        print("new message received")
        if aStream == inputStream {
            var dataBuffer = Array<UInt8>(repeating: 0, count: 1024)
            var length: Int
            while (inputStream?.hasBytesAvailable)! {
                length = (inputStream?.read(&dataBuffer, maxLength: 1024))!
                if length > 0 {
                    let output = String(bytes: dataBuffer, encoding: .ascii)
                    if nil != output {
                        print("server said: \(output ?? "")")
                        messageReceived(message: output!)
                    }
                }
            }
        }

    case Stream.Event.endEncountered:
        aStream.close()
        aStream.remove(from: RunLoop.current, forMode: .defaultRunLoopMode)
        print("close stream")
    case Stream.Event.errorOccurred:
        print("error: \(aStream.streamError?.localizedDescription ?? "")")
    case Stream.Event.hasSpaceAvailable:
        print("has space available")
    case Stream.Event.openCompleted:
        print("Opened")
    default:
        print("some other event...")
        break
    }
}
func messageReceived(message: String){
    print("messageReceived :",message)
    lblOutput.stringValue = message
}

func send(message: String){

    let strSend = message
    let buffer = [UInt8](message.utf8)
    if let _ = strSend.data(using: .ascii) {
        outputStream?.write(buffer, maxLength: buffer.count)
    }

    print("messageSent :",message)
    close()

}

}

1 个答案:

答案 0 :(得分:0)

我找到了上述问题的答案。

func setupConnection(){
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, "localhost" as CFString, 6688, &readStream, &writeStream)
open()}

将上面的代码替换为:

func setupConnection(){
Stream.getStreamsToHost(withName: "localhost", port: 6688, inputStream: &self.inputStream, outputStream: &self.outputStream)
open()}