I need some help in IOS Socket programming. I have implemented a successful TCP Socket connection between IOS and a Java Server, however I found that it is imposible to reconnect it after the socket fails (I disconnect my network and reconnect it).
That’s the code I use to open the streams:
- (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];
}
}
And when I receive a NSStreamEventErrorOccurred or a NSStreamEventEndEncountered I try to close the connection and reconnect again.
I close it with:
-(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;
}
The problem is that the socket is not reconnecting again… I am thinking on using SmallSockets or CocoaAsyncSockets to see if I can reconnect the socket… Do you see any implementation problem? Do you recommend using SmallSockets or CocoaAsyncSockets??
Thank you in advance!!
Finally I did implement it with CocoaAsyncSockets https://github.com/robbiehanson/CocoaAsyncSocket and it was really easy doing a reconnection with this socket.
First I initialize the socket object:
To connect I use:
And then you can use the delegate to do reconnection whenever it failed:
I found very easy to use that library. I hope that helps anyone.
Thanks a lot.