如何测试我的远程套接字NSStream是否正确打开

时间:2015-02-22 07:08:45

标签: sockets swift ios8 nsstream

  

TL; DR:在调用NSStream.getStreamsToHostWithName(...)后检查我的远程流是否正确打开的方法是什么?

我的应用程序是移动IOS8 swift应用程序。

我正在使用NSStream与远程服务器进行输入和输出套接字通信。

要连接到我的服务器并打开我的流,我使用以下代码:

func connect(host: String, port: Int) -> Bool
{
    //clear the previous connection if existing (and update self.connected)
    disconnect()
    //updating the current connection
    self.host = host
    self.port = port

    //pairing NSstreams with remote connection
    NSStream.getStreamsToHostWithName(self.host!, port: self.port!, inputStream: &inputStream, outputStream: &outputStream)

    if (self.inputStream != nil && self.outputStream != nil)
    {
        //open streams
        self.inputStream?.open()
        self.outputStream?.open()
    }
    if self.outputStream?.streamError == nil && self.inputStream?.streamError == nil
    {
        println("SOK")    //PROBLEM 1
    }
    //error checking after opening streams // PROBLEM 2
    if var inputStreamErr: CFError = CFReadStreamCopyError(self.inputStream)?
    {
        println("InputStream error : " + CFErrorCopyDescription(inputStreamErr))
    }
    else if var outputStreamErr: CFError = CFWriteStreamCopyError(self.outputStream)?
    {
        println("OutStream error : " + CFErrorCopyDescription(outputStreamErr))
    }
    else
    {
        //set the delegate to self
        self.inputStream?.delegate = self
        self.outputStream?.delegate = self
        self.connected = true
    }
    //return connection state
    return self.connected
}

我的问题位于// PROBLEM1和// PROBLEM2。

在这些点上,我尝试确定我的套接字是否正确打开,但即使服务器未运行,此代码仍然有效,则读取和写入操作失败。 我希望能够确定连接是否失败。

也许我完全错了,我不知道如何测试它。

1 个答案:

答案 0 :(得分:28)

首先,您必须schedule the stream on a runloop

inputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)

而且,在您的代码中,检查错误还为时过早。由于open()是异步操作,因此您必须使用delegate等待结果。这是一个有效的例子:

import Foundation

class Connection: NSObject, NSStreamDelegate {
var host:String?
var port:Int?
var inputStream: NSInputStream?
var outputStream: NSOutputStream?

func connect(host: String, port: Int) {

    self.host = host
    self.port = port

    NSStream.getStreamsToHostWithName(host, port: port, inputStream: &inputStream, outputStream: &outputStream)

    if inputStream != nil && outputStream != nil {

        // Set delegate
        inputStream!.delegate = self
        outputStream!.delegate = self

        // Schedule
        inputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
        outputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)

        print("Start open()")

        // Open!
        inputStream!.open()
        outputStream!.open()
    }
}

func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
    if aStream === inputStream {
        switch eventCode {
        case NSStreamEvent.ErrorOccurred:
            print("input: ErrorOccurred: \(aStream.streamError?.description)")
        case NSStreamEvent.OpenCompleted:
            print("input: OpenCompleted")
        case NSStreamEvent.HasBytesAvailable:
            print("input: HasBytesAvailable")

            // Here you can `read()` from `inputStream`

        default:
            break
        }
    }
    else if aStream === outputStream {
        switch eventCode {
        case NSStreamEvent.ErrorOccurred:
            print("output: ErrorOccurred: \(aStream.streamError?.description)")
        case NSStreamEvent.OpenCompleted:
            print("output: OpenCompleted")
        case NSStreamEvent.HasSpaceAvailable:
            print("output: HasSpaceAvailable")

            // Here you can write() to `outputStream`

        default:
            break
        }
    }
}

}

然后:

let conn = Connection()
conn.connect("www.example.com", port: 80)