We have made the chat app for iphone using java chat server.
We have used socket for this. On iOS side we have used following code ;
#import <CFNetwork/CFNetwork.h>
#import <sys/socket.h>
#import <sys/types.h>
- (void) viewDidLoad
{
[self initNetworkCommunication];
}
#pragma mark Network connection
- (void) initNetworkCommunication
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"xx.xx.xx.xx", xxxx, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
But whenever the app goes in background , the socket disconnects. So, we have to make socket "KEEP ALIVE"
.
On server side , we have achieved this by socket.setKeepAlive(true, 2000);
, but we cant be able to set this on app (i.e iOS) side.
We have searched on these links - Link1 and Link2
They have specified to use code like following to make socket keep alive ;
CFDataRef data = (CFDataRef)CFWriteStreamCopyProperty(( CFWriteStreamRef)outputStream, kCFStreamPropertySocketNativeHandle);
if(data)
{
CFSocketNativeHandle socket_handle = *(CFSocketNativeHandle *)CFDataGetBytePtr(data);
CFRelease(data);
NSLog(@"SOCK HANDLE: %x", socket_handle);
//Enabling keep alive
if( setsockopt( socket_handle, SOL_SOCKET, SO_KEEPALIVE, &opt, sizeof( opt ) ) < 0 )
{
NSLog(@"Yikes 2: failed to set keepalive! ERRNO: %s", strerror(errno));
}
}
We have tried this code but could not be able to find the vales of socket_handle, SOL_SOCKET, SO_KEEPALIVE, &opt, sizeof( opt )
variables.
So how to to make socket connection keep alive in ios (objective-c) ?
Thanks.
didEnterBackground
and reopen inwillEnterForeground
, but I cannot really advise you here. "Technical Note TN2277" seems to contain valuable information, perhaps you start with that. - Your question was "how to set SO_KEEPALIVE on a socket", but your real problem seems to be "how to handle open connections when the app goes into background". That are different things, so you might consider updating your question or perhaps start at new one. – Martin R