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

How to test if my remote socket NSStream are correctly open

TL;DR : What's the way to check if my remote stream are opened correctly after a call to 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。

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

也许我做的完全错了,我不知道如何测试这个。

首先,你必须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)