https://github.com/potato512/SYDemo_SYSocket
通常使用网络进行文件的断点续传时,都是文件的断点下载,很少有文件的断点上传的例子。现在通过socket方式做了一个文件的断点上传。socket使用了AsyncSocket,或是GCDAsyncSocket。
AsyncSocket:http://code.google.com/p/cocoaasyncsocket/
GCDAsyncSocket:https://github.com/robbiehanson/CocoaAsyncSocket
在使用时,先将socket进行了封装。然后再使用封装类。
封装类文件
// .h文件
//
// SocketManager.h
// zhangshaoyu
//
// Created by zhangshaoyu on 15/9/22.
// Copyright (c) 2015年 zhangshaoyu. All rights reserved.
// socket断点上传文件
#import <Foundation/Foundation.h>
/// 掉线类型(服务端掉线,或用户主动退出)
typedef NS_ENUM(NSInteger, SocketDisconnectType)
{
/// 服务器掉线,默认为0
SocketOfflineByServer = 0,
/// 用户主动cut
SocketOfflineByUser = 1
};
@interface SocketManager : NSObject
/// 掉线类型
@property (nonatomic, assign) SocketDisconnectType disconnecType;
/// 文件路径
@property (nonatomic, copy) NSString *filePath;
/// 单例
+ (SocketManager *)sharedSocket;
/// socket连接
- (void)socketConnectWithHost:(NSString *)host port:(UInt16)port;
/// socket连接断开
- (void)socketDisconnect;
/// GCDSocket连接
- (void)GCDSocketConnectWithHost:(NSString *)host port:(UInt16)port;;
/// GCDSocket连接断开
- (void)GCDSocketDisconnect;
@end
// .m文件
//
// SocketManager.m
// zhangshaoyu
//
// Created by zhangshaoyu on 15/9/22.
// Copyright (c) 2015年 zhangshaoyu. All rights reserved.
//
#import "SocketManager.h"
#import "AsyncSocket.h"
#import "GCDAsyncSocket.h"
unsigned long long OffSet = 1024 * 200;
static NSInteger const timeWithout = -1;
static NSInteger const tagWriteData = 1;
static NSInteger const tagReadData = 2;
static NSString *const keyOffset = @"keyOffset";
static NSString *const keySouceId = @"keySouceId";
@interface SocketManager () <AsyncSocketDelegate, GCDAsyncSocketDelegate>
@property (nonatomic, strong) GCDAsyncSocket *GCDSocket;
@property (nonatomic, strong) AsyncSocket *socket; // socket
@property (nonatomic, copy) NSString *socketHost; // socket的Host
@property (nonatomic, assign) UInt16 socketPort; // socket的prot
@property (nonatomic, strong) NSTimer *socketTimer; // 计时器
@property (nonatomic, assign) BOOL isUploadHead; // 文件上传头文件协议
@property (nonatomic, assign) unsigned long long filelength; // 文件上传大小
@property (nonatomic, strong) NSString *fileName; // 文件上传名称
@property (nonatomic, strong) NSString *