AsyncSocket.h解读

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

#import 

@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

你可能感兴趣的:(AsyncSocket.h解读)