简体   繁体   中英

How to set “KEEP ALIVE” for socket connection in iOS?

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 (ie 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.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

on your .m file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM