真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

IOS上的socket通信-創(chuàng)新互聯(lián)

客戶端:
導入頭文件:
#import
#import
#import
#import

1. 創(chuàng)建連接
CFSocketContext sockContext = {0, // 結(jié)構(gòu)體的版本,必須為0
self,  // 一個任意指針的數(shù)據(jù),可以用在創(chuàng)建時CFSocket對象相關(guān)聯(lián)。這個指針被傳遞給所有的上下文中定義的回調(diào)。
NULL, // 一個定義在上面指針中的retain的回調(diào), 可以為NULL
NULL, NULL};

CFSocketRef _socket = (kCFAllocatorDefault, // 為新對象分配內(nèi)存,可以為nil
PF_INET, // 協(xié)議族,如果為0或者負數(shù),則默認為PF_INET
SOCK_STREAM, // 套接字類型,如果協(xié)議族為PF_INET,則它會默認為SOCK_STREAM
IPPROTO_TCP, // 套接字協(xié)議,如果協(xié)議族是PF_INET且協(xié)議是0或者負數(shù),它會默認為IPPROTO_TCP
kCFSocketConnectCallBack, // 觸發(fā)回調(diào)函數(shù)的socket消息類型,具體見Callback Types
TCPServerConnectCallBack, // 上面情況下觸發(fā)的回調(diào)函數(shù)
&sockContext // 一個持有CFSocket結(jié)構(gòu)信息的對象,可以為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]);  // 把字符串的地址轉(zhuǎn)換為機器可識別的網(wǎng)絡地址

    // 把sockaddr_in結(jié)構(gòu)體中的地址轉(zhuǎn)換為Data
    CFDataRef address = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&addr4, sizeof(addr4));
    CFSocketConnectToAddress(_socket, // 連接的socket
address, // CFDataRef類型的包含上面socket的遠程地址的對象
-1  // 連接超時時間,如果為負,則不嘗試連接,而是把連接放在后臺進行,如果_socket消息類型為kCFSocketConnectCallBack,將會在連接成功或失敗的時候在后臺觸發(fā)回調(diào)函數(shù)
);

    CFRunLoopRef cRunRef = CFRunLoopGetCurrent();    // 獲取當前線程的循環(huán)
    // 創(chuàng)建一個循環(huán),但并沒有真正加如到循環(huán)中,需要調(diào)用CFRunLoopAddSource
    CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _socket, 0);
    CFRunLoopAddSource(cRunRef, // 運行循環(huán)
    sourceRef,  // 增加的運行循環(huán)源, 它會被retain一次
    kCFRunLoopCommonModes  // 增加的運行循環(huán)源的模式
    );
    CFRelease(courceRef);
}

2. 設(shè)置回調(diào)函數(shù)
// socket回調(diào)函數(shù)的格式:
static void TCPServerConnectCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
    if (data != NULL) {
        // 當socket為kCFSocketConnectCallBack時,失敗時回調(diào)失敗會返回一個錯誤代碼指針,其他情況返回NULL
        NSLog(@"連接失敗");
        return;
    }
    TCPClient *client = (TCPClient *)info;
    // 讀取接收的數(shù)據(jù)
    [info performSlectorInBackground:@selector(readStream) withObject:nil];


3. 接收發(fā)送數(shù)據(jù)
// 讀取接收的數(shù)據(jù)
- (void)readStream {
    char buffer[1024];
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    while (recv(CFSocketGetNative(_socket), //與本機關(guān)聯(lián)的Socket 如果已經(jīng)失效返回-1:INVALID_SOCKET
          buffer, sizeof(buffer), 0)) {
        NSLog(@"%@", [NSString stringWithUTF8String:buffer]);
    }
}

// 發(fā)送數(shù)據(jù)
- (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回調(diào)函數(shù),同客戶端
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;
        // 創(chuàng)建一個可讀寫的socket連接
        CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &iStream, &oStream);
        if (iStream && oStream) {
            CFStreamClientContext streamContext = {0, NULL, NULL, NULL};
            if (!CFReadStreamSetClient(iStream, kCFStreamEventHasBytesAvaiable,
                                      readStream, // 回調(diào)函數(shù),當有可讀的數(shù)據(jù)時調(diào)用
                                      &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);
        }
    }
}

// 讀取數(shù)據(jù)
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!");
    }
}

// 開辟一個線程線程函數(shù)中
void runLoopInThread() {
    int res = setupSocket();
    if (!res) {
        exit(1);
    }
    CFRunLoopRun();    // 運行當前線程的CFRunLoop對象
}

成都創(chuàng)新互聯(lián)服務項目包括延吉網(wǎng)站建設(shè)、延吉網(wǎng)站制作、延吉網(wǎng)頁制作以及延吉網(wǎng)絡營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,延吉網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務的客戶以成都為中心已經(jīng)輻射到延吉省份的部分城市,未來相信會繼續(xù)擴大服務區(qū)域并繼續(xù)獲得客戶的支持與信任!

另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。


網(wǎng)頁標題:IOS上的socket通信-創(chuàng)新互聯(lián)
鏈接分享:http://weahome.cn/article/dcicoc.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部