iOS FTP文件傳輸客戶端CFStream/NSStream自實現

最近在做一個FTP客戶端項目,項目開始是基于CFReadStreamCreateWithFTPURL系列方法的第三方實現的。但是在用CFFTP方法遇到了一個問題,背景如下:
傳輸模式采用被動模式,FTP服務器位于路由器后面,做好端口映射后,在公網訪問FTP服務器發(fā)送PASV指令時,服務器返回了內網IP地址,CFFTP報錯。按理說這應該是服務器配置的問題,但是PC、安卓卻能夠完成傳輸,然后領導讓我自己解決。那么問題來了,CFFTP你就不能用command的ip來給data socket連一下?

最后只能放棄CFFTP,關注到后面的“Use NSURLSession ...”讓我又研究了好幾天NSURLSession關于FTP的相關信息,也沒有結果,只看到了一些HTTP的信息
圖1.png

然后就打算自己實現FTP網絡方法了。FTP文件傳輸協(xié)議是基于TCP的,屬于分層網絡協(xié)議中的應用層。

#import <Foundation/Foundation.h>

@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流來收發(fā)信息的。

- (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得到流的狀態(tài)。也不用不像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];
}

這里在上傳文件的時候需要支持斷點續(xù)傳,開始的時候沒找到NSStream設置偏移量的方法,所以采用的NSFileHandle來獲取數據,這里通過NSStream或者NSFileHandle來讀取本地文件都是可以的。

FTP要完成一個文件操作時,需要發(fā)送一系列的指令;具體需要發(fā)送哪些命令可以使用其他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)]      //創(chuàng)建目錄
#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指令也是枚舉類型,發(fā)送指令時通過調用方法- (void)send:(SendMessage)smsg來獲取完成發(fā)送操作

- (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激發(fā) 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激發(fā) 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;
        }
    }
    // 如果登錄失敗,不繼續(xù)執(zhí)行下面的命令
    if (!_isLogin)
        return;
    
    for (int i = 0; i < operations.count; i++) {
        SendMessage sendm = [operations[i] integerValue];
        // 設置過Type就跳過
        if (sendm==SendType && _isType==YES) {
            continue;
        }
        // 發(fā)送操作
        [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;
        }
    }
}

還有一些對服務器響應的處理代碼,我直接把代碼鏈接貼出來可以交流學習一下。
下載鏈接

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容