2014-09-04 17 views
0

我要创建套接字连接多设备,和我有一个接受回拨功能如何在AcceptCallBack创建新的线程时套接字创建iOS中

void AcceptCallBack(
        CFSocketRef socket, 
        CFSocketCallBackType type, 
        CFDataRef address, 
        const void *data, 
        void *info) 
{ 
    CFReadStreamRef readStream = NULL; 
    CFWriteStreamRef writeStream = NULL; 
    CFIndex bytes; 
    UInt8 buffer[128]; 
    UInt8 recv_len = 0, send_len = 0; 

    /* The native socket, used for various operations */ 
    CFSocketNativeHandle sock = *(CFSocketNativeHandle *) data; 

    /* The punch line we stored in the socket context */ 
    char *punchline = info; 

    /* Create the read and write streams for the socket */ 
    CFStreamCreatePairWithSocket(kCFAllocatorDefault, sock, 
           &readStream, &writeStream); 

    if (!readStream || !writeStream) { 
     close(sock); 
     fprintf(stderr, "CFStreamCreatePairWithSocket() failed\n"); 
     return; 
    } 

    CFReadStreamOpen(readStream); 
    CFWriteStreamOpen(writeStream); 

    /* Wait for the client to finish sending the joke; wait for newline */ 
    // How to create a new IOS thread from here to read data from client. 

} 

我想从客户端监听数据创建NSThread。因为这是一个C++函数,我无法从对象C访问变量。 谢谢。

+0

下面的答案是否有帮助? – Echelon 2014-09-08 09:35:54

回答

0

您在这里有几个选项。

  1. 你可以写在一个新的.mm文件的目标C辅助函数,并从你的C++代码中调用它

  2. 可以更改C++文件有一个.mm扩展。这样你可以将Objective C代码和C++混合在一起。你可能会需要一些包括魔像这样在文件的顶部: -

#ifdef __OBJC__ // prevent C++ compiler errors #import <Foundation/Foundation.h> #endif

3.You也应该看看使用GCD代替。它使用C接口,并可能使用dispatch_async()来完成您所需的一切。因为dispatch_async()使用块,所以如果您仍然使用.cpp文件扩展名,则需要设置-fblocks编译器标志。