AsyncSocket.h解读

原文链接:
http://www.cnblogs.com/worldtraveler/archive/2012/12/22/2829067.html

#import <Foundation/Foundation.h>

@class AsyncSocket;//async异步的 synchro同步
@class AsyncReadPacket;
@class AsyncWritePacket;

//extern来说可以理解为扩展吧是这样的是从一个类扩展到另一个类中的
extern NSString *const AsyncSocketException;//Exception:意外
extern NSString *const AsyncSocketErrorDomin;//errorDomin :错误域名

enum AsyncSocketError//socket错误
{
    AsynsocketCFSocketError = kCFSocketError,// kCFSocketError is from CFSocketError enum;
    AsyncSocketNoError = 0,//never used
    AsyncSocketCanceledError,//onSocketWillConnect :return NO
    AsyncSocketReadTimmeoutError,
    AsyncSocketWritrTimeoutError
};
typedef enum AsyncSocketError AsyncSocketError;//typedef

@interface NSObject (AsyncSocketDelegate)//类目,虽然看上去像是代理方法,但是作者把它们写成了NSObject类的扩展方法 因此实际编程中包含该.h文件的所有类都可以直接使用这些方法


/**
 * In the event of an error, the socket is closed.
 * You may call "unreadData" during this call-back to get the last bit of data off the socket.
 * When connecting, this delegate method may be called
 * before"onSocket:didAcceptNewSocket:" or "onSocket:didConnectToHost:".
 **/
//发生错误 socket将要断开连接
-(void) onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err;

/**
 * Called when a socket accepts a connection.  Another socket is spawned to handle it. The new socket will have
 * the same delegate and will call "onSocket:didConnectToHost:port:".
 **/
//在socket断开连接时将被执行(不管有没有发生错误)。如果你想在一个socket断开连接后release它,do so here。在“onSocket:willDisconnectWithError中那样做是不安全的
-(void)onSocketDidDisconnect:(AsyncSocket *)socket;

/**
 * Called when a socket accepts a connection.  Another socket is spawned to handle it. The new socket will have
 * the same delegate and will call "onSocket:didConnectToHost:port:".
 **/
//called when 一个socket接受了一个连接(connection),会产生另一个新的socket去处理这个连接(好像是服务器中用的那个,sock是监听(listen)socket,接受到连接后会产生新的socket去处理连接)。新产生的socket将存在相同的代理,而且会call "onSocket:didConnectToHost:port:".
-(void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket;

/**
 * Called when a new socket is spawned to handle a connection.  This method should return the run-loop of the
 * thread on which the new socket and its delegate should operate. If omitted, [NSRunLoop currentRunLoop] is used.
 **/
//omitted:省略,遗漏
//called when一个新socket被产生去处理一个连接。这个方法将会返回这个新socket和它的代理将要操作的线程(thread)的运行回路(runloop)
-(NSRunLoop *)onSocket:(AsyncSocket *)sock wantsRunLoopForNewSocket:(AsyncSocket *)newSocket;

/**
 * Called when a socket is about to connect. This method should return YES to continue, or NO to abort. 
 * If aborted, will result in AsyncSocketCanceledError.
 *
 * If the connectToHost:onPort:error: method was called, the delegate will be able to access and configure the
 * CFReadStream and CFWriteStream as desired prior to connection.
 *
 * If the connectToAddress:error: method was called, the delegate will be able to access and configure the
 * CFSocket and CFSocketNativeHandle (BSD socket) as desired prior to connection. You will be able to access and
 * configure the CFReadStream and CFWriteStream in the onSocket:didConnectToHost:port: method.
 **/
//abort:使流产,使中止 prior:优先的,在。。。之前 configure:配置,设定
//be about to :是指将要做某事,或是发生某事,是指可以预见的,并且确定要发生的
//在一个socket将要连接时被调用。要继续连接,则让该方法返回YES,要中止连接,则让该方法返回NO。如果中止(返回NO)将会导致AsyncSocketCanceledError。
//如果connectToHost:onPort:error: 方法在这之前被调用过,这个代理方法可以进入到之前想要进行的连接,并配置CFReadStream和CFWriteStream
-(BOOL)onSocketWillConnect:(AsyncSocket *)socket;

/**
 * Called when a socket connects and is ready for reading and writing.
 * The host parameter will be an IP address, not a DNS name.
 **/
//called when 一个socket已经连接,并且已经准备读写。host参数是IP地址,而不是DNS域名
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port;

/**
 * Called when a socket has completed reading the requested data into memory.
 * Not called if there is an error.
 **/
//当一个socket已经把数据读入内存中时被调用。如果发生错误则不被调用
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;

/**
 * Called when a socket has read in data, but has not yet completed the read.
 * This would occur if using readToData: or readToLength: methods.
 * It may be used to for things such as updating progress bars.
 **/
//当一个socket已经读入数据但是还没有读完的时候被调用。在使用readToData: 或者 readToLength:方法的时候可能会产生这种情况。它在某些情况下可以被使用:比如说更新进度条
- (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(CFIndex)partialLength tag:(long)tag;

/**
 * Called when a socket has completed writing the requested data. Not called if there is an error.
 **/
//当一个socket完全写完数据时被调用。发生错误则不调用。
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag;
@end


@interface AsyncSocket : NSObject 
{
    CFSocketRef theSocket; //IPv4 accept or connect socket
    CFSocketRef theSocket6;//Ipv6 accept or connect socket
    CFReadStreamRef theReadStream;
    CFWriteStreamRef theWriteStream;
    
    CFRunLoopSourceRef theSource;//for theSocket
    CFRunLoopSourceRef theSource6;//for theSocket6
    CFRunLoopRef theRunLoop;
    CFSocketContext theContext;
    
    NSMutableArray *theReadqueue;
    AsyncReadPacket *theCurrentRead;
    NSTimer *theReadTimer;
    NSMutableData *partailReadBuffer;
    
    NSMutableArray *theWriteQueue;
    AsyncWritePacket *theCurrentWrite;
    NSTimer *theWriteTimer;
    
    id theDelegate;
    Byte theFlags;
    
    long theUserData;
}

-(id)init;
-(id)initWithDelegate:(id)delegate;
-(id)initWithDelegate:(id)delegate userData:(long)userData;

-(NSString *)description;//重定义%@打印出的string

/**
 * Use "canSafelySetDelegate" to see if there is any pending business (reads and writes) with the current delegate
 * before changing it.  It is, of course, safe to change the delegate before connecting or accepting connections.
 **/
//在改变代理之前使用canSafelySetDelegate方法来查看是否有当前代理还没做完的事情(读或者写)。
//在连接或接受连接之前改变代理是安全的。
- (id)delegate;
- (BOOL)canSafelySetDelegate;
- (void)setDelegate:(id)delegate;

/*User data can be a long,or an id or void* cast to a long.  */
//cast to:投射
-(long)userData;
-(void)setUserData:(long)userData;

/*Don't use these to read or write. And don't close them,either!  */
-(CFSocketRef)getCFSocket;
-(CFReadStreamRef)getCFReadStream;
-(CFWriteStreamRef)getCFWriteStream;

/**
 * Once one of these methods is called, the AsyncSocket instance is locked in, and the rest can't be called without
 * disconnecting the socket first.  If the attempt times out or fails, these methods either return NO or
 * call "onSocket:willDisconnectWithError:" and "onSockedDidDisconnect:".
 **/
//
- (BOOL)acceptOnPort:(UInt16)port error:(NSError **)errPtr;
- (BOOL)acceptOnAddress:(NSString *)hostaddr port:(UInt16)port error:(NSError **)errPtr;
- (BOOL)connectToHost:(NSString *)hostname onPort:(UInt16)port error:(NSError **)errPtr;
- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;

-(void)disconnect;
-(void)disconnectAfterWriting;
-(BOOL)isConnected;
-(NSString *)connectedHost;
-(UInt16)connectedPort;
-(BOOL)isIPv4;
-(BOOL)isIPv6;

/**
 * The following methods won't block. To not time out, use a negative time interval.
 * If they time out, "onSocket:disconnectWithError:" is called. The tag is for your convenience.
 * You can use it as an array index, step number, state id, pointer, etc., just like the socket's user data.
 **/

//下面这些方法不会阻塞。如果想没有timeout 使用一个负数time interval
//如果time out时间用光了,会调用"onSocket:disconnectWithError:"方法。tag只是为了方便,就像socket中的user data一样。

/**
 * This will read a certain number of bytes into memory, and call the delegate method when those bytes have been read.
 * If there is an error, partially read data is lost.
 * If the length is 0, this method does nothing and the delegate is not called.
 **/
//这个方法会从内存中读入特定数值的字节,读完之后会调用代理方法
//如果发生错误,被部分读入的数据会消失
//如果length为0,这个方法什么都不做,代理也不会被调用
-(void)readDataToLength:(CFIndex)length withTimeout:(NSTimeInterval)timeout tag:(long)tag;

/**
 * This reads bytes until (and including) the passed "data" parameter, which acts as a separator.
 * The bytes and the separator are returned by the delegate method.
 *
 * If you pass nil or zero-length data as the "data" parameter,
 * the method will do nothing, and the delegate will not be called.
 *
 * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
 * Note that this method is not character-set aware, so if a separator can occur naturally as part of the encoding for
 * a character, the read will prematurely end.
 **/

-(void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;

/**
 * Reads the first available bytes that become available on the socket.
 **/

-(void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;


/* Writes data to the socket, and calls the delegate when finished.
 *
 * If you pass in nil or zero-length data, this method does nothing and the delegate will not be called.
 **/
//向调用方法的socket写入数据
-(void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;

/**
 * Returns progress of current read or write, from 0.0 to 1.0, or NaN if no read/write (use isnan() to check).
 * "tag", "done" and "total" will be filled in if they aren't NULL.
 **/
//返回当前读/写的进度(0.0~1.0),没有读/写时返回NaN,在tag,done,total非空时要写上
//typedef signed long CFIndex;
-(float)progressOfReadReturningTag:(long *)tag bytesDone:(CFIndex *)done total:(CFIndex *)total;
-(float)progressOfWriteReturningTag:(long *)tag bytesDone:(CFIndex *)done total:(CFIndex *)total;

/**
 * In the event of an error, this method may be called during onSocket:willDisconnectWithError: to read
 * any data that's left on the socket.
 **/
//在发生错误的时候,这个方法可能在onSocket:willDisconnectWithError:中被调用,用来读取留在socket中的数据
- (NSData *)unreadData;

+(NSData *)unreadData;//0x0D0A
+(NSData *)CRLFData;//0x0D
+(NSData *)LFData;//0x0A
+(NSData *)ZeroData;//0x00
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容

  • 曾经有一份美好的爱情放在我的面前我没有珍惜。等到失去后才后悔莫及。如果可以再对小李说。毛欣想说。这辈子无缘再牵手。...
    毛欣与小李阅读 2,562评论 0 13
  • 当孩子还是个小宝宝,我们经常毫不吝啬的对孩子表达:“我最爱你了,你是我在世界上最爱的人”丝毫不嫌肉麻,我也一样。但...
    林悠然PET阅读 740评论 4 7
  • 50+践行第七天 我的抱怨来自于不公平的待遇,我想通过抱怨来让他明白,明白我所受的委屈,明白他的不公平的对待,我知...
    李李青青阅读 158评论 1 0
  • 我想写一封信给自己,生命无常,不管是对未来的期望还是对意外的来临,我都不懂为什么,突然就失去方向,这封信并不是提...
    Y凰阅读 251评论 0 1
  • 两个项目遇到ShareSDK 分享到QQ和QQ空间失败问题 1.第一个项目QQ失败显示 : iOS qq 第三方登...
    sttech阅读 7,220评论 0 1