我正在使用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...
}
}
答案 0 :(得分:0)
文档说明:
除非客户端正在轮询流,否则它负责确保在至少一个运行循环上调度流,并确保正在调度流的至少一个运行循环在运行。
您正在轮询流。通常,这不是要使用流的方式,但是既然如此,就不需要运行循环。