从Stream获取套接字

时间:2013-05-02 17:58:37

标签: objective-c cocoa sockets stream

我正在使用以下代码打开一个将文件发送到FTP的流。我需要的是从这里获得套接字,以便我可以实现这里发布的第二个代码。

    self.networkStream = CFBridgingRelease(
                                           CFWriteStreamCreateWithFTPURL(NULL, (__bridge CFURLRef) url)
                                           );
    assert(self.networkStream != nil);

    if ([usernameText length] != 0) {
        success = [self.networkStream setProperty:usernameText forKey:(id)kCFStreamPropertyFTPUserName];
        assert(success);
        success = [self.networkStream setProperty:passwordText forKey:(id)kCFStreamPropertyFTPPassword];
        assert(success);
    }

    self.networkStream.delegate = self;
    [self.networkStream setProperty:(id)kCFBooleanFalse forKey:(id)kCFStreamPropertyFTPAttemptPersistentConnection];
    [self.networkStream setProperty:(id)kCFBooleanTrue forKey:(id)kCFStreamPropertyShouldCloseNativeSocket];

    [self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.networkStream open];

CFSocketRef cfsock = [sock getCFSocket]; 
CFSocketNativeHandle rawsock = CFSocketGetNative(cfsock); 
int flag = 1; 
int result = setsockopt(rawsock, IPPROTO_TCP, TCP_NODELAY,
                    (char *)&flag, sizeof(int)); 
if (result != 0)
    NSLog(@\"Could Not Disable Nagle...\");
else
    NSLog(@\"Nagle Is Disabled.\");

第二个块需要一个套接字才能执行,我只有一个流,并且不知道如何从套接字中取出套接字。

感谢

1 个答案:

答案 0 :(得分:2)

在写入流上调用CFWriteStreamCopyProperty()并指定kCFStreamPropertySocketNativeHandle以获取包含基础CFSocketNativeHandle的CFDataRef。然后,您可以使用CFDataGetBytes()

提取套接字
CFSocketNativeHandle rawsock;
CFDataRef socketData =
  CFWriteStreamCopyProperty((__bridge CFWriteStreamRef)(self.networkstream),
                            kCFStreamPropertySocketNativeHandle);
CFDataGetBytes(socketData,
               CFRangeMake(0, sizeof(CFSocketNativeHandle)),
               (UInt8 *)&rawsock);
CFRelease(socketData);

/* Make use of rawsock */