CFSocket — TCP

来源:互联网 发布:印度理工学院 知乎 编辑:程序博客网 时间:2024/06/06 01:06

CFSocketContext CTX = {0,self,NULL,NULL,NULL};    _socket =CFSocketCreate(                            kCFAllocatorDefault,                            PF_INET,                            SOCK_STREAM,                            IPPROTO_TCP,                            kCFSocketConnectCallBack,     //                             ServerConnectCallBack,    // CALLBACK                             &CTX                             );        ////////////////////////////SET ADDRESS///////////////////   struct sockaddr_in addr;   memset(&addr, 0,sizeof(addr));    addr.sin_len =sizeof(addr);    addr.sin_family =AF_INET;    addr.sin_port =htons(port.intValue);    addr.sin_addr.s_addr =inet_addr([server UTF8String]);       CFDataRef address = CFDataCreate(                                    kCFAllocatorDefault,                                     (UInt8*)&addr,                                    sizeof(addr));        /////////////////////////////IMPlement/////////////////////    //CFTimeInterval timeout = 15000.0f ; // how long to wait before returning       CFSocketError connectRC = CFSocketConnectToAddress(_socket,address,1);       if(connectRC == kCFSocketSuccess ){        //get the current runLoop object and set this runLoop to source        CFRunLoopRef cfrl =CFRunLoopGetCurrent();  //get the current runLoop        CFRunLoopSourceRef  source =CFSocketCreateRunLoopSource(kCFAllocatorDefault,_socket,0);//       CFRunLoopAddSource(cfrl,source,kCFRunLoopCommonModes);//       CFRelease(source);       int nNetTimeout = 1;       setsockopt(CFSocketGetNative(_socket),SOL_SOCKET, SO_NOSIGPIPE, (void*)&nNetTimeout,sizeof(int));    }