我需要 IOS Socket 编程方面的帮助。我已经在 IOS 和 Java 服务器之间实现了一个成功的 TCP Socket 连接,但是我发现在套接字失败后重新连接它是不可能的(我断开我的网络并重新连接它)。
这是我用来打开流的代码:
- (void)initCommunication{
@try {
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"XXX.XXX.XXX.XXX", 4454, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
//Asignamos los delegates
inputStream.delegate = self;
outputStream.delegate = self;
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
connected = true;
}
}
@catch (NSException *exception) {
connected = false;
NSLog(@"Error connecting socket: %@", exception.reason);
[self checkConnection];
}
}
当我收到 NSStreamEventErrorOccurred 或 NSStreamEventEndEncountered 时,我会尝试关闭连接并重新连接。
我关闭它:
-(void) close{
[inputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream close];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream setDelegate:nil];
inputStream = nil;
[outputStream setDelegate:nil];
outputStream = nil;
connected = false;
}
问题是套接字没有再次重新连接......我正在考虑使用 SmallSockets 或 CocoaAsyncSockets 看看我是否可以重新连接套接字......你看到任何实现问题吗?你推荐使用 SmallSockets 还是 CocoaAsyncSockets?
先感谢您!!