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

然后就打算自己實(shí)現(xiàn)FTP網(wǎng)絡(luò)方法了。FTP文件傳輸協(xié)議是基于TCP的,屬于分層網(wǎng)絡(luò)協(xié)議中的應(yīng)用層。
#import <Foundation/Foundation.h>
@interface YHHFtpRequest : NSObject
@property (nonatomic, strong) NSString *ftpUser;
@property (nonatomic, strong) NSString *ftpPassword;
@property (nonatomic, strong) NSString *serversPath; // 服務(wù)器文件全路徑,如:(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
主要需要實(shí)現(xiàn)的功能接口就這些
我這邊主要采用被動(dòng)模式的連接方式,所以就主要研究了下被動(dòng)模式相關(guān)的知識(shí):
1.命令端口:我這邊采用的是CFStream流來(lái)收發(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設(shè)置了回調(diào)
CFReadStreamSetClient(readStream, kCFStreamEventHasBytesAvailable|kCFStreamEventErrorOccurred|kCFStreamEventEndEncountered, ReadStreamClientCallBack, &context);
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
_read = readStream;
_write = writeStream;
CFReadStreamOpen(readStream);
CFWriteStreamOpen(writeStream);
}
這里采用CFStream是因?yàn)镾tream流獲取信息方便,也能夠簡(jiǎn)單的通過(guò)CFStreamEventType得到流的狀態(tài)。也不用不像CFSocket要多加幾個(gè)頭文件。
2.數(shù)據(jù)端口:
- (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];
}
這里在上傳文件的時(shí)候需要支持?jǐn)帱c(diǎn)續(xù)傳,開(kāi)始的時(shí)候沒(méi)找到NSStream設(shè)置偏移量的方法,所以采用的NSFileHandle來(lái)獲取數(shù)據(jù),這里通過(guò)NSStream或者NSFileHandle來(lái)讀取本地文件都是可以的。
FTP要完成一個(gè)文件操作時(shí),需要發(fā)送一系列的指令;具體需要發(fā)送哪些命令可以使用其他FTP客戶端(FileZiIla)查看。
這里拿上傳舉例:
登錄(USER)->密碼(PASS)->指定目錄(CWD)->設(shè)置數(shù)據(jù)格式(TYPE)->獲取文件大小(SIZE)->設(shè)置被動(dòng)模式(PASV)->上傳(APPE/STOR)
每一個(gè)操作都要等前面一個(gè)指令得到正確的響應(yīng)后才能進(jìn)行。我這里考慮的方法是把完成一個(gè)操作的所有命令做成枚舉加到一個(gè)數(shù)組里面,要做什么操作就拿對(duì)應(yīng)數(shù)組遍歷。
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)]
這里把文件操作做成了枚舉類型,F(xiàn)TP指令也是枚舉類型,發(fā)送指令時(shí)通過(guò)調(diào)用方法- (void)send:(SendMessage)smsg來(lái)獲取完成發(fā)送操作
- (BOOL)login {
NSArray *operations = OPERATION_LOGIN;
if (!_semaphore) {
_semaphore = dispatch_semaphore_create(0);
}
// 加在在主線程的原因是需要添加到runloop,最好是可以開(kāi)個(gè)子線程,啟動(dòng)該線程的runloop。
dispatch_async(dispatch_get_main_queue(), ^{
[self setupCommandSocket];
});
// 等待commandSocket連接到服務(wù)器,接收歡迎消息
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];
// 設(shè)置過(guò)Type就跳過(guò)
if (sendm==SendType && _isType==YES) {
continue;
}
// 發(fā)送操作
[self send:sendm];
// 等待響應(yīng)
NSLog(@"等待");
long res = dispatch_semaphore_wait(_semaphore, dispatch_time(DISPATCH_TIME_NOW, 20*NSEC_PER_SEC));
if (res != 0 || _failure) {
// error
_failure = NO;
break;
}
}
}
還有一些對(duì)服務(wù)器響應(yīng)的處理代碼,我直接把代碼鏈接貼出來(lái)可以交流學(xué)習(xí)一下。
下載鏈接