How to test if my remote socket NSStream are correctly open

前端 未结 1 1362
借酒劲吻你
借酒劲吻你 2021-02-02 04:24

TL;DR : What\'s the way to check if my remote stream are opened correctly after a call to NSStream.getStreamsToHostWithName(...)?

相关标签:
1条回答
  • 2021-02-02 04:58

    First of all, you have to schedule the stream on a runloop:

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

    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
            }
        }
    }
    
    }
    

    Then:

    let conn = Connection()
    conn.connect("www.example.com", port: 80)
    
    0 讨论(0)
提交回复
热议问题