iOS FTP文件传输客户端CFStream/NSStream自实现

最近在做一个FTP客户端项目,项目开始是基于CFReadStreamCreateWithFTPURL系列方法的第三方实现的。但是在用CFFTP方法遇到了一个问题,背景如下:
传输模式采用被动模式,FTP服务器位于路由器后面,做好端口映射后,在公网访问FTP服务器发送PASV指令时,服务器返回了内网IP地址,CFFTP报错。按理说这应该是服务器配置的问题,但是PC、安卓却能够完成传输,然后领导让我自己解决。那么问题来了,CFFTP你就不能用command的ip来给data socket连一下?

最后只能放弃CFFTP,关注到后面的“Use NSURLSession ...”让我又研究了好几天NSURLSession关于FTP的相关信息,也没有结果,只看到了一些HTTP的信息
图1.png

然后就打算自己实现FTP网络方法了。FTP文件传输协议是基于TCP的,属于分层网络协议中的应用层。

#import 

@interface YHHFtpRequest : NSObject

@property (nonatomic, strong) NSString *ftpUser;
@property (nonatomic, strong) NSString *ftpPassword;
@property (nonatomic, strong) NSString *serversPath; // 服务器文件全路径,如:(ftp://xx.xx.xx.xx:21/XXX/xx.jpg) (ftp://) 可以略
@property (nonatomic, strong) NSString *localPath; // 本地文件全路径

- (void)download:(BOOL)resume
 progress:(void(^)(Float32 percent, NSUInteger finishSize))progress
 complete:(void(^)(id respond, NSError *error))complete;

- (void)upload:(BOOL)resume
 progress:(void(^)(Float32 percent, NSUInteger finishSize))progress
 complete:(void(^)(id respond, NSError *error))complete;

- (void)list:(void(^)(id respond, NSError *error))complete;
- (void)createDirctory:(NSString *)name complete:(void(^)(id respond, NSError *error))complete;
- (void)deleteDirctory:(NSString *)name complete:(void(^)(id respond, NSError *error))complete;
- (void)deleteFile:(NSString *)name complete:(void(^)(id respond, NSError *error))complete;
- (void)rename:(NSString *)newName complete:(void(^)(id respond, NSError *error))complete;

@end

主要需要实现的功能接口就这些


我这边主要采用被动模式的连接方式,所以就主要研究了下被动模式相关的知识:
1.命令端口:我这边采用的是CFStream流来收发信息的。

- (void)setupCommandSocket {
    CFStreamClientContext context = {0, (__bridge void *)self, NULL, NULL, NULL};
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)_host, _port, &readStream, &writeStream);
    //这里我只需要管收到的消息,所以就只给readStream设置了回调
    CFReadStreamSetClient(readStream, kCFStreamEventHasBytesAvailable|kCFStreamEventErrorOccurred|kCFStreamEventEndEncountered, ReadStreamClientCallBack, &context);
    
    CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    
    _read = readStream;
    _write = writeStream;
    
    CFReadStreamOpen(readStream);
    CFWriteStreamOpen(writeStream);
}

这里采用CFStream是因为Stream流获取信息方便,也能够简单的通过CFStreamEventType得到流的状态。也不用不像CFSocket要多加几个头文件。
2.数据端口:

- (void)setupDataSocket:(NSString *)ip {
    NSArray *arr = [ip componentsSeparatedByString:@":"];
    
    NSString *host = arr.firstObject;
    UInt32 port = [arr.lastObject intValue];
    
    NSInputStream *input;
    NSOutputStream *output;
    
    if (_ctype >= OperateUpload) {  //上传
        [NSStream getStreamsToHostWithName:host port:port inputStream:nil outputStream:&output];
        input = [NSInputStream inputStreamWithFileAtPath:_localPath];
        [input setProperty:@(_location) forKey:NSStreamFileCurrentOffsetKey];
        //        _handle = [NSFileHandle fileHandleForReadingAtPath:_localPath];
        //        [_handle seekToFileOffset:_location];
    }else {
        [NSStream getStreamsToHostWithName:host port:port inputStream:&input outputStream:nil];
        output = [NSOutputStream outputStreamToFileAtPath:_localPath append:(_ctype == OperateDownloadResume)];
    }
    
    input.delegate = self;
    output.delegate = self;
    
 
    [input scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [output scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
    _input = input;
    _output = output;
    
    [_output open];
    //    [_input open];
}

这里在上传文件的时候需要支持断点续传,开始的时候没找到NSStream设置偏移量的方法,所以采用的NSFileHandle来获取数据,这里通过NSStream或者NSFileHandle来读取本地文件都是可以的。

FTP要完成一个文件操作时,需要发送一系列的指令;具体需要发送哪些命令可以使用其他FTP客户端(FileZiIla)查看。
这里拿上传举例:

登录(USER)->密码(PASS)->指定目录(CWD)->设置数据格式(TYPE)->获取文件大小(SIZE)->设置被动模式(PASV)->上传(APPE/STOR)

每一个操作都要等前面一个指令得到正确的响应后才能进行。我这里考虑的方法是把完成一个操作的所有命令做成枚举加到一个数组里面,要做什么操作就拿对应数组遍历。

typedef NS_ENUM(NSInteger, OperateType) {
    OperateCreateD,
    OperateDeleteD,
    OperateDelete,
    OperateRename,
    OperateList,
    OperateDownload,
    OperateDownloadResume,
    OperateUpload,
    OperateUploadResume
};
#define OPERATIONS                  @[OPERATION_CREATE_D, OPERATION_DELETE_D, OPERATION_DELETE, OPERATION_RENAME, OPERATION_LIST, OPERATION_DOWNLOAD, OPERATION_DOWNLOAD_RESUME, OPERATION_UPLOAD, OPERATION_UPLOAD_RESUME]

#define OPERATION_LOGIN             @[@(SendUser), @(SendPASS)]
#define OPERATION_CREATE_D          @[@(SendCWD),  @(SendMKD)]      //创建目录
#define OPERATION_DELETE_D          @[@(SendCWD),  @(SendRMD)]      //删除目录
#define OPERATION_DELETE            @[@(SendCWD),  @(SendDELE)]
#define OPERATION_RENAME            @[@(SendRNFR), @(SendRNTO)]
#define OPERATION_LIST              @[@(SendCWD),  @(SendType), @(SendPASV), @(SendMLSD)]
#define OPERATION_DOWNLOAD          @[@(SendCWD),  @(SendType), @(SendSize), @(SendPASV), @(SendRETR)]
#define OPERATION_DOWNLOAD_RESUME   @[@(SendCWD),  @(SendType), @(SendSize), @(SendPASV), @(SendREST), @(SendRETR)]
#define OPERATION_UPLOAD            @[@(SendCWD),  @(SendType), @(SendPASV), @(SendSTOR)]
#define OPERATION_UPLOAD_RESUME     @[@(SendCWD),  @(SendType), @(SendSize), @(SendPASV), @(SendAPPE)]

这里把文件操作做成了枚举类型,FTP指令也是枚举类型,发送指令时通过调用方法- (void)send:(SendMessage)smsg来获取完成发送操作

- (BOOL)login {
    
    NSArray *operations = OPERATION_LOGIN;
    if (!_semaphore) {
        _semaphore = dispatch_semaphore_create(0);
    }
    
    // 加在在主线程的原因是需要添加到runloop,最好是可以开个子线程,启动该线程的runloop。
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setupCommandSocket];
    });
    // 等待commandSocket连接到服务器,接收欢迎消息
    NSLog(@"等待");
    long res = dispatch_semaphore_wait(_semaphore, dispatch_time(DISPATCH_TIME_NOW, 200*NSEC_PER_SEC));
    // 如果由dispatch_semaphore_signal激发 res==0
    if (res != 0 || _failure) {
        NSLog(@"connect error");
        return NO;
    }
    
    // 登陆操作
    for (int i = 0; i < operations.count; i++) {
        SendMessage sendm = [operations[i] integerValue];
        [self send:sendm];
        
        NSLog(@"等待");
        long res = dispatch_semaphore_wait(_semaphore, dispatch_time(DISPATCH_TIME_NOW, 20*NSEC_PER_SEC));
        // 如果由dispatch_semaphore_signal激发 res==0
        if (res != 0 || _failure) {
            NSLog(@"error");
            return NO;
        }
    }
    //    return _isLogin;
    return YES;
}
- (void)yhh_operate:(OperateType)operate {
    NSArray *operations = OPERATIONS[operate];
    
    if (!_isLogin) {
        if (!(_isLogin = [self login])) {
            NSLog(@"login error");
            return;
        }
    }
    // 如果登录失败,不继续执行下面的命令
    if (!_isLogin)
        return;
    
    for (int i = 0; i < operations.count; i++) {
        SendMessage sendm = [operations[i] integerValue];
        // 设置过Type就跳过
        if (sendm==SendType && _isType==YES) {
            continue;
        }
        // 发送操作
        [self send:sendm];
        // 等待响应
        NSLog(@"等待");
        long res = dispatch_semaphore_wait(_semaphore, dispatch_time(DISPATCH_TIME_NOW, 20*NSEC_PER_SEC));
        if (res != 0 || _failure) {
            // error
            _failure = NO;
            break;
        }
    }
}

还有一些对服务器响应的处理代码,我直接把代码链接贴出来可以交流学习一下。
下载链接

你可能感兴趣的:(iOS FTP文件传输客户端CFStream/NSStream自实现)