亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

IOS上的socket通信

發布時間:2020-06-27 21:52:37 來源:網絡 閱讀:678 作者:卓行天下 欄目:移動開發

客戶端:
導入頭文件:
#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對象
}

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

安徽省| 巴南区| 平江县| 德州市| 乌兰察布市| 唐海县| 广汉市| 柘城县| 西畴县| 沙田区| 松江区| 枝江市| 新兴县| 千阳县| 前郭尔| 南和县| 长岛县| 隆安县| 林甸县| 邻水| 望奎县| 涞水县| 丁青县| 深泽县| 杭锦后旗| 克什克腾旗| 肥西县| 东海县| 嘉兴市| 孙吴县| 富平县| 泉州市| 绥阳县| 邵阳县| 张家界市| 吉安县| 调兵山市| 晴隆县| 盖州市| 南川市| 乾安县|