从流获取套接字



我使用下面的代码打开一个流发送文件到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.");

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

谢谢

在写流上调用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 */

相关内容

  • 没有找到相关文章

最新更新