如何测试我的远程套接字NSStream是否正确打开 [英] How to test if my remote socket NSStream are correctly open

查看:161
本文介绍了如何测试我的远程套接字NSStream是否正确打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


TL; DR:在调用 NSStream.getStreamsToHostWithName(...)?

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

My application is a mobile IOS8 swift application.

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

I am using NSStream for input and output socket communication with a remote server.

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

To connect to my server and open my stream I use this code:

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。

My problem is located at //PROBLEM1 and //PROBLEM2.

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

At these points I try to determine if my sockets are opened correctly, but even if the server is not running this code still works, then the read and write operations are failing. I would like to be able to determine if the connection failed or not.

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

Maybe I am doing it totally wrong, I don't get how to test this.

推荐答案

首先,你必须在runloop上安排流

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

而且,在你的代码中,检查错误还为时过早。因为 open()是异步操作,所以必须使用 delegate 等待结果。以下是工作示例:

And, in your code, it's too soon to check the error. Because open() is async operation, you have to wait the result using delegate. Here is working example:

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)

这篇关于如何测试我的远程套接字NSStream是否正确打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆