轉 iOS socket

http://www.cocoachina.com/industry/20130830/6904.htmlhtml

 

 

 

客戶端: 服務器

導入頭文件: 
#import <sys/socket.h> 
#import <netinet/in.h> 
#import <arpa/inet.h> 
#import <unistd.h> 
 
1. 建立鏈接 
CFSocketContext sockContext = {0, // 結構體的版本,必須爲0 
self,  // 一個任意指針的數據,能夠用在建立時CFSocket對象相關聯。這個指針被傳遞給全部的上下文中定義的回調。 
NULL, // 一個定義在上面指針中的retain的回調, 能夠爲NULL 
NULL, NULL}; 
 
CFSocketRef _socket = (kCFAllocatorDefault, // 爲新對象分配內存,能夠爲nil 
PF_INET, // 協議族,若是爲0或者負數,則默認爲PF_INET 
SOCK_STREAM, // 套接字類型,若是協議族爲PF_INET,則它會默認爲SOCK_STREAM 
IPPROTO_TCP, // 套接字協議,若是協議族是PF_INET且協議是0或者負數,它會默認爲IPPROTO_TCP 
kCFSocketConnectCallBack, // 觸發回調函數的socket消息類型,具體見Callback Types 
TCPServerConnectCallBack, // 上面狀況下觸發的回調函數 
&sockContext // 一個持有CFSocket結構信息的對象,能夠爲nil 
); 
 
if (_socket != nil) { 
    struct sockaddr_in addr4;   // IPV4 
    memset(&addr4, 0, sizeof(addr4)); 
    addr4.sin_len = sizeof(addr4); 
    addr4.sin_family = AF_INET; 
    addr4.sin_port = htons(8888); 
    addr4.sin_addr.s_addr = inet_addr([strAddress UTF8String]);  // 把字符串的地址轉換爲機器可識別的網絡地址 
        
    // 把sockaddr_in結構體中的地址轉換爲Data 
    CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&addr4, sizeof(addr4)); 
    CFSocketConnectToAddress(_socket, // 鏈接的socket 
address, // CFDataRef類型的包含上面socket的遠程地址的對象 
-1  // 鏈接超時時間,若是爲負,則不嘗試鏈接,而是把鏈接放在後臺進行,若是_socket消息類型爲kCFSocketConnectCallBack,將會在鏈接成功或失敗的時候在後臺觸發回調函數 
); 
 
    CFRunLoopRef cRunRef = CFRunLoopGetCurrent();    // 獲取當前線程的循環 
    // 建立一個循環,但並無真正加如到循環中,須要調用CFRunLoopAddSource 
    CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _socket, 0); 
    CFRunLoopAddSource(cRunRef, // 運行循環 
    sourceRef,  // 增長的運行循環源, 它會被retain一次 
    kCFRunLoopCommonModes  // 增長的運行循環源的模式 
    ); 
    CFRelease(courceRef); 
} 
 
2. 設置回調函數 
// socket回調函數的格式: 
static void TCPServerConnectCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { 
    if (data != NULL) { 
        // 當socket爲kCFSocketConnectCallBack時,失敗時回調失敗會返回一個錯誤代碼指針,其餘狀況返回NULL 
        NSLog(@"鏈接失敗"); 
        return; 
    } 
    TCPClient *client = (TCPClient *)info; 
    // 讀取接收的數據 
    [info performSlectorInBackground:@selector(readStream) withObject:nil]; 
 
 
3. 接收發送數據 
// 讀取接收的數據 
- (void)readStream { 
    char buffer[1024]; 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    while (recv(CFSocketGetNative(_socket), //與本機關聯的Socket 若是已經失效返回-1:INVALID_SOCKET 
           buffer, sizeof(buffer), 0)) { 
        NSLog(@"%@", [NSString stringWithUTF8String:buffer]); 
    } 
} 
 
// 發送數據 
- (void)sendMessage { 
    NSString *stringTosend = @"你好"; 
    char *data = [stringTosend UTF8String]; 
    send(SFSocketGetNative(_socket), data, strlen(data) + 1, 0); 
} 
 
 
服務器端: 
 
CFSockteRef _socket; 
CFWriteStreamRef outputStream = NULL; 
 
int setupSocket() { 
    _socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, TCPServerAcceptCallBack, NULL); 
    if (NULL == _socket) { 
        NSLog(@"Cannot create socket!"); 
        return 0; 
    } 
    
    int optval = 1; 
    setsockopt(CFSocketGetNative(_socket), SOL_SOCKET, SO_REUSEADDR, // 容許重用本地地址和端口 
(void *)&optval, sizeof(optval)); 
    
    struct sockaddr_in addr4; 
    memset(&addr4, 0, sizeof(addr4)); 
    addr4.sin_len = sizeof(addr4); 
    addr4.sin_family = AF_INET; 
    addr4.sin_port = htons(port); 
    addr4.sin_addr.s_addr = htonl(INADDR_ANY); 
    CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&addr4, sizeof(addr4)); 
    
    if (kCFSocketSuccess != CFSocketSetAddress(_socket, address)) { 
        NSLog(@"Bind to address failed!"); 
        if (_socket) 
             CFRelease(_socket); 
        _socket = NULL; 
        return 0; 
    } 
        
    CFRunLoopRef cfRunLoop = CFRunLoopGetCurrent(); 
    CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _socket, 0); 
    CFRunLoopAddSource(cfRunLoop, source, kCFRunLoopCommonModes); 
    CFRelease(source); 
    
    return 1; 
} 
 
// socket回調函數,同客戶端 
void TCPServerAcceptCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { 
    if (kCFSocketAcceptCallBack == type) { 
        // 本地套接字句柄 
        CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data; 
        uint8_t name[SOCK_MAXADDRLEN];       
        socklen_t nameLen = sizeof(name); 
        if (0 != getpeername(nativeSocketHandle, (struct sockaddr *)name, &nameLen)) { 
            NSLog(@"error"); 
            exit(1); 
        } 
        NSLog(@"%@ connected.", inet_ntoa( ((struct sockaddr_in *)name)->sin_addr )): 
 
        CFReadStreamRef iStream; 
        CFWriteStreamRef oStream; 
        // 建立一個可讀寫的socket鏈接 
        CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &iStream, &oStream);  
        if (iStream && oStream) { 
            CFStreamClientContext streamContext = {0, NULL, NULL, NULL}; 
            if (!CFReadStreamSetClient(iStream, kCFStreamEventHasBytesAvaiable, 
                                       readStream, // 回調函數,當有可讀的數據時調用 
                                       &streamContext)){ 
                exit(1); 
            } 
 
            if (!CFReadStreamSetClient(iStream, kCFStreamEventCanAcceptBytes, writeStream, &streamContext)){ 
                exit(1); 
            } 
 
            CFReadStreamScheduleWithRunLoop(iStream, CFRunLoopGetCurrent(), kCFRunLoopCommomModes); 
            CFWriteStreamScheduleWithRunLoop(wStream, CFRunLoopGetCurrent(), kCFRunLoopCommomModes); 
            CFReadStreamOpen(iStream); 
            CFWriteStreamOpen(wStream); 
        } else { 
             close(nativeSocketHandle);  
        } 
    } 
} 
 
// 讀取數據 
void readStream(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) { 
    UInt8 buff[255]; 
    CFReadStreamRead(stream, buff, 255); 
    printf("received: %s", buff); 
} 
 
void writeStream (CFWriteStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) { 
    outputStream = stream; 
} 
 
main { 
    char *str = "nihao"; 
    
    if (outputStream != NULL) { 
        CFWriteStreamWrite(outputStream, str, strlen(line) + 1); 
    } else { 
        NSLog(@"Cannot send data!"); 
    } 
} 
 
// 開闢一個線程線程函數中 
void runLoopInThread() { 
    int res = setupSocket(); 
    if (!res) { 
        exit(1); 
    } 
    CFRunLoopRun();    // 運行當前線程的CFRunLoop對象 
}
網絡

相關文章
相關標籤/搜索