我寫了這個代碼設置一個流與服務器:NSStream TCP保持活躍的iOS
-(void)streamOpenWithIp:(NSString *)ip withPortNumber:(int)portNumber;
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)ip, portNumber, &readStream, &writeStream);
if(readStream && writeStream)
{
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
//Setup inpustream
inputStream = (__bridge NSInputStream *)readStream;
[inputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
//Setup outputstream
outputStream = (__bridge NSOutputStream *)writeStream;
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];
}
}
我能夠連接到服務器併發送&接收數據。但我想檢查連接是否仍然存在。如果我從WiFi路由器斷開連接線,我仍然可以在流中發送數據並且沒有發生錯誤。
您可以通過使用定時器發送一些消息並檢查您是否收到回覆,在應用程序級別解決此問題。但是,您也可以在較低級別上使用TCP Keep-Alive技術來解決此問題。
如何使用NSStream實現這個功能?我怎樣才能設置檢查間隔?
我假設您通過TCP Keep-Alive檢查流時關閉了NSStreamEventErrorOcurred?
我已經檢查了這個職位,但我無法弄清楚: Keeping a socket connection alive in iOS
感謝您的幫助!
是的,我當然使用這種方法!但是如果我從無線路由器斷開UTP電纜,流不會給我一個錯誤!這就是爲什麼我想使用TCP保持活着。 –
它應該打印流狀態8或16. – meth
它給了我錯誤描述,當我寫錯誤事件像(NSStreamStatus)NSStreamEventErrorOccurred: – meth