2013-05-14 119 views
0

我們使用java聊天服務器爲iPhone製作了聊天應用程序。如何在iOS中爲套接字連接設置「KEEP ALIVE」?

我們爲此使用了套接字。在iOS端我們使用了下面的代碼;

#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]; 

} 

但是,只要應用程序在後臺運行,套接字就會斷開連接。所以,我們必須製造插座"KEEP ALIVE"

在服務器端,我們已經通過socket.setKeepAlive(true, 2000);實現了這一點,但我們無法在應用程序(即iOS)上設置它。

我們已搜查這些鏈接 - Link1Link2

他們指定使用的代碼像下面使插座保持活躍;

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)); 
     } 
    } 

我們已經嘗試過這種代碼,但不能能夠找到socket_handle, SOL_SOCKET, SO_KEEPALIVE, &opt, sizeof(opt)變量的瓦萊斯。

那麼如何讓套接字連接在ios(objective-c)中保持活躍?

謝謝。您.m文件

+0

[這](http://stackoverflow.com/questions/11387560/keeping-a-socket-connection-alive-in-ios)後可能會幫助你,讓我瞭解洞察力。祝你好運 – 2013-05-14 05:52:30

+0

@DipenPanchasara:這就是問題中提到的「Link1」:-) – 2013-05-14 05:54:24

+0

這是否有幫助:http://stackoverflow.com/a/15787080/1187415? - 別忘了'#include '。 – 2013-05-14 05:56:21

回答

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

相關問題