InputStream ios 在没有 RunLoop 的情况下工作

InputStream ios works without a RunLoop

我正在使用 InputStream 和 OutputStream 编写 iOS 应用程序。但是,我发现我可以从流中读取和写入,而无需在 RunLoop 中调度它们!

我这里是我的ThreadFunc。请注意,我已经注释掉了所有的 runLoop 代码,但它仍然有效!

@objc func threadFunc(){
    var dataToSend: Data?;

    print("Inside threadFunc loop!");

    //self.m_ReadStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.commonModes );
    self.m_ReadStream!.open();

    //self.m_WriteStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.commonModes );
    self.m_WriteStream!.open()

    var once = false;

    while( !m_Calcelled ){
        let wStat = self.m_WriteStream?.streamStatus;
        let rStat = self.m_ReadStream?.streamStatus;

        if( dataToSend == nil && self.m_Lock.lock(before: Date(timeIntervalSinceNow: 10 ) )){
            dataToSend = self.m_DataToSend; // Make local copy
            self.m_DataToSend = nil;
            self.m_Lock.unlock();
        }

        if( dataToSend != nil && wStat == .open ){
            let totalBytesSent = self.sendDataBlock( d:dataToSend! );
            if( totalBytesSent == dataToSend?.count ){
                print("successfully sent the packet.");
            }
        }
        //let untilDate: Date = Date(timeIntervalSinceNow: 5 );
        //print("SocketThread. Calling runLoop...");
        //RunLoop.current.run( mode: .defaultRunLoopMode, before: untilDate );
        //print("SocketThread is waiting for action....");
        //sleep(1);   // Sleep for 1 second...
    }
}

如文档所述:

Unless the client is polling the stream, it is responsible for ensuring that the stream is scheduled on at least one run loop and that at least one of the run loops on which the stream is scheduled is being run.

您正在轮询流。这通常不是流的使用方式,但既然你是,它不需要运行循环。