PageRenderTime 7ms CodeModel.GetById 3ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 1ms

/Vendor/CocoaAsyncSocket/GCDAsyncSocket.h

https://github.com/ipmcc/CocoaHTTPServer
C++ Header | 1083 lines | 204 code | 108 blank | 771 comment | 0 complexity | 52498ee530846a21cc7461051266e231 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1//  
   2//  GCDAsyncSocket.h
   3//  
   4//  This class is in the public domain.
   5//  Originally created by Robbie Hanson in Q3 2010.
   6//  Updated and maintained by Deusty LLC and the Apple development community.
   7//  
   8//  https://github.com/robbiehanson/CocoaAsyncSocket
   9//
  10
  11#import <Foundation/Foundation.h>
  12#import <Security/Security.h>
  13#import <Security/SecureTransport.h>
  14#import <dispatch/dispatch.h>
  15
  16@class GCDAsyncReadPacket;
  17@class GCDAsyncWritePacket;
  18@class GCDAsyncSocketPreBuffer;
  19
  20#if TARGET_OS_IPHONE
  21
  22  // Compiling for iOS
  23
  24  #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 50000 // iOS 5.0 supported
  25  
  26    #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000 // iOS 5.0 supported and required
  27
  28      #define IS_SECURE_TRANSPORT_AVAILABLE      YES
  29      #define SECURE_TRANSPORT_MAYBE_AVAILABLE   1
  30      #define SECURE_TRANSPORT_MAYBE_UNAVAILABLE 0
  31
  32    #else                                         // iOS 5.0 supported but not required
  33
  34      #ifndef NSFoundationVersionNumber_iPhoneOS_5_0
  35        #define NSFoundationVersionNumber_iPhoneOS_5_0 881.00
  36      #endif
  37
  38      #define IS_SECURE_TRANSPORT_AVAILABLE     (NSFoundationVersionNumber >= NSFoundationVersionNumber_iPhoneOS_5_0)
  39      #define SECURE_TRANSPORT_MAYBE_AVAILABLE   1
  40      #define SECURE_TRANSPORT_MAYBE_UNAVAILABLE 1
  41
  42    #endif
  43
  44  #else                                        // iOS 5.0 not supported
  45
  46    #define IS_SECURE_TRANSPORT_AVAILABLE      NO
  47    #define SECURE_TRANSPORT_MAYBE_AVAILABLE   0
  48    #define SECURE_TRANSPORT_MAYBE_UNAVAILABLE 1
  49
  50  #endif
  51
  52#else
  53
  54  // Compiling for Mac OS X
  55
  56  #define IS_SECURE_TRANSPORT_AVAILABLE      YES
  57  #define SECURE_TRANSPORT_MAYBE_AVAILABLE   1
  58  #define SECURE_TRANSPORT_MAYBE_UNAVAILABLE 0
  59
  60#endif
  61
  62extern NSString *const GCDAsyncSocketException;
  63extern NSString *const GCDAsyncSocketErrorDomain;
  64
  65extern NSString *const GCDAsyncSocketQueueName;
  66extern NSString *const GCDAsyncSocketThreadName;
  67
  68#if SECURE_TRANSPORT_MAYBE_AVAILABLE
  69extern NSString *const GCDAsyncSocketSSLCipherSuites;
  70#if TARGET_OS_IPHONE
  71extern NSString *const GCDAsyncSocketSSLProtocolVersionMin;
  72extern NSString *const GCDAsyncSocketSSLProtocolVersionMax;
  73#else
  74extern NSString *const GCDAsyncSocketSSLDiffieHellmanParameters;
  75#endif
  76#endif
  77
  78enum GCDAsyncSocketError
  79{
  80	GCDAsyncSocketNoError = 0,           // Never used
  81	GCDAsyncSocketBadConfigError,        // Invalid configuration
  82	GCDAsyncSocketBadParamError,         // Invalid parameter was passed
  83	GCDAsyncSocketConnectTimeoutError,   // A connect operation timed out
  84	GCDAsyncSocketReadTimeoutError,      // A read operation timed out
  85	GCDAsyncSocketWriteTimeoutError,     // A write operation timed out
  86	GCDAsyncSocketReadMaxedOutError,     // Reached set maxLength without completing
  87	GCDAsyncSocketClosedError,           // The remote peer closed the connection
  88	GCDAsyncSocketOtherError,            // Description provided in userInfo
  89};
  90typedef enum GCDAsyncSocketError GCDAsyncSocketError;
  91
  92////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  93#pragma mark -
  94////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  95
  96@interface GCDAsyncSocket : NSObject <NSSecureCoding>
  97
  98/**
  99 * GCDAsyncSocket uses the standard delegate paradigm,
 100 * but executes all delegate callbacks on a given delegate dispatch queue.
 101 * This allows for maximum concurrency, while at the same time providing easy thread safety.
 102 * 
 103 * You MUST set a delegate AND delegate dispatch queue before attempting to
 104 * use the socket, or you will get an error.
 105 * 
 106 * The socket queue is optional.
 107 * If you pass NULL, GCDAsyncSocket will automatically create it's own socket queue.
 108 * If you choose to provide a socket queue, the socket queue must not be a concurrent queue.
 109 * If you choose to provide a socket queue, and the socket queue has a configured target queue,
 110 * then please see the discussion for the method markSocketQueueTargetQueue.
 111 * 
 112 * The delegate queue and socket queue can optionally be the same.
 113**/
 114- (id)init;
 115- (id)initWithSocketQueue:(dispatch_queue_t)sq;
 116- (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq;
 117- (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq;
 118
 119#pragma mark Configuration
 120
 121- (id)delegate;
 122- (void)setDelegate:(id)delegate;
 123- (void)synchronouslySetDelegate:(id)delegate;
 124
 125- (dispatch_queue_t)delegateQueue;
 126- (void)setDelegateQueue:(dispatch_queue_t)delegateQueue;
 127- (void)synchronouslySetDelegateQueue:(dispatch_queue_t)delegateQueue;
 128
 129- (void)getDelegate:(id *)delegatePtr delegateQueue:(dispatch_queue_t *)delegateQueuePtr;
 130- (void)setDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
 131- (void)synchronouslySetDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
 132
 133- (void)setupReadAndWriteSourcesForNewlyConnectedSocket;
 134
 135
 136/**
 137 * By default, both IPv4 and IPv6 are enabled.
 138 * 
 139 * For accepting incoming connections, this means GCDAsyncSocket automatically supports both protocols,
 140 * and can simulataneously accept incoming connections on either protocol.
 141 * 
 142 * For outgoing connections, this means GCDAsyncSocket can connect to remote hosts running either protocol.
 143 * If a DNS lookup returns only IPv4 results, GCDAsyncSocket will automatically use IPv4.
 144 * If a DNS lookup returns only IPv6 results, GCDAsyncSocket will automatically use IPv6.
 145 * If a DNS lookup returns both IPv4 and IPv6 results, the preferred protocol will be chosen.
 146 * By default, the preferred protocol is IPv4, but may be configured as desired.
 147**/
 148- (BOOL)isIPv4Enabled;
 149- (void)setIPv4Enabled:(BOOL)flag;
 150
 151- (BOOL)isIPv6Enabled;
 152- (void)setIPv6Enabled:(BOOL)flag;
 153
 154- (BOOL)isIPv4PreferredOverIPv6;
 155- (void)setPreferIPv4OverIPv6:(BOOL)flag;
 156
 157/**
 158 * User data allows you to associate arbitrary information with the socket.
 159 * This data is not used internally by socket in any way.
 160**/
 161- (id)userData;
 162- (void)setUserData:(id)arbitraryUserData;
 163
 164#pragma mark Accepting
 165
 166/**
 167 * Tells the socket to begin listening and accepting connections on the given port.
 168 * When a connection is accepted, a new instance of GCDAsyncSocket will be spawned to handle it,
 169 * and the socket:didAcceptNewSocket: delegate method will be invoked.
 170 * 
 171 * The socket will listen on all available interfaces (e.g. wifi, ethernet, etc)
 172**/
 173- (BOOL)acceptOnPort:(uint16_t)port error:(NSError **)errPtr;
 174
 175/**
 176 * This method is the same as acceptOnPort:error: with the
 177 * additional option of specifying which interface to listen on.
 178 * 
 179 * For example, you could specify that the socket should only accept connections over ethernet,
 180 * and not other interfaces such as wifi.
 181 * 
 182 * The interface may be specified by name (e.g. "en1" or "lo0") or by IP address (e.g. "192.168.4.34").
 183 * You may also use the special strings "localhost" or "loopback" to specify that
 184 * the socket only accept connections from the local machine.
 185 * 
 186 * You can see the list of interfaces via the command line utility "ifconfig",
 187 * or programmatically via the getifaddrs() function.
 188 * 
 189 * To accept connections on any interface pass nil, or simply use the acceptOnPort:error: method.
 190**/
 191- (BOOL)acceptOnInterface:(NSString *)interface port:(uint16_t)port error:(NSError **)errPtr;
 192
 193- (BOOL)bindOnInterface:(NSString *)interface port:(uint16_t)port error:(NSError **)errPtr;
 194
 195- (BOOL)acceptOnBoundInterfaceError:(NSError **)errPtr;
 196
 197#pragma mark Connecting
 198
 199/**
 200 * Connects to the given host and port.
 201 * 
 202 * This method invokes connectToHost:onPort:viaInterface:withTimeout:error:
 203 * and uses the default interface, and no timeout.
 204**/
 205- (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)errPtr;
 206
 207/**
 208 * Connects to the given host and port with an optional timeout.
 209 * 
 210 * This method invokes connectToHost:onPort:viaInterface:withTimeout:error: and uses the default interface.
 211**/
 212- (BOOL)connectToHost:(NSString *)host
 213               onPort:(uint16_t)port
 214          withTimeout:(NSTimeInterval)timeout
 215                error:(NSError **)errPtr;
 216
 217/**
 218 * Connects to the given host & port, via the optional interface, with an optional timeout.
 219 * 
 220 * The host may be a domain name (e.g. "deusty.com") or an IP address string (e.g. "192.168.0.2").
 221 * The host may also be the special strings "localhost" or "loopback" to specify connecting
 222 * to a service on the local machine.
 223 * 
 224 * The interface may be a name (e.g. "en1" or "lo0") or the corresponding IP address (e.g. "192.168.4.35").
 225 * The interface may also be used to specify the local port (see below).
 226 * 
 227 * To not time out use a negative time interval.
 228 * 
 229 * This method will return NO if an error is detected, and set the error pointer (if one was given).
 230 * Possible errors would be a nil host, invalid interface, or socket is already connected.
 231 * 
 232 * If no errors are detected, this method will start a background connect operation and immediately return YES.
 233 * The delegate callbacks are used to notify you when the socket connects, or if the host was unreachable.
 234 * 
 235 * Since this class supports queued reads and writes, you can immediately start reading and/or writing.
 236 * All read/write operations will be queued, and upon socket connection,
 237 * the operations will be dequeued and processed in order.
 238 * 
 239 * The interface may optionally contain a port number at the end of the string, separated by a colon.
 240 * This allows you to specify the local port that should be used for the outgoing connection. (read paragraph to end)
 241 * To specify both interface and local port: "en1:8082" or "192.168.4.35:2424".
 242 * To specify only local port: ":8082".
 243 * Please note this is an advanced feature, and is somewhat hidden on purpose.
 244 * You should understand that 99.999% of the time you should NOT specify the local port for an outgoing connection.
 245 * If you think you need to, there is a very good chance you have a fundamental misunderstanding somewhere.
 246 * Local ports do NOT need to match remote ports. In fact, they almost never do.
 247 * This feature is here for networking professionals using very advanced techniques.
 248**/
 249- (BOOL)connectToHost:(NSString *)host
 250               onPort:(uint16_t)port
 251         viaInterface:(NSString *)interface
 252          withTimeout:(NSTimeInterval)timeout
 253                error:(NSError **)errPtr;
 254
 255/**
 256 * Connects to the given address, specified as a sockaddr structure wrapped in a NSData object.
 257 * For example, a NSData object returned from NSNetService's addresses method.
 258 * 
 259 * If you have an existing struct sockaddr you can convert it to a NSData object like so:
 260 * struct sockaddr sa  -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
 261 * struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
 262 * 
 263 * This method invokes connectToAdd
 264**/
 265- (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
 266
 267/**
 268 * This method is the same as connectToAddress:error: with an additional timeout option.
 269 * To not time out use a negative time interval, or simply use the connectToAddress:error: method.
 270**/
 271- (BOOL)connectToAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr;
 272
 273/**
 274 * Connects to the given address, using the specified interface and timeout.
 275 * 
 276 * The address is specified as a sockaddr structure wrapped in a NSData object.
 277 * For example, a NSData object returned from NSNetService's addresses method.
 278 * 
 279 * If you have an existing struct sockaddr you can convert it to a NSData object like so:
 280 * struct sockaddr sa  -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
 281 * struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
 282 * 
 283 * The interface may be a name (e.g. "en1" or "lo0") or the corresponding IP address (e.g. "192.168.4.35").
 284 * The interface may also be used to specify the local port (see below).
 285 * 
 286 * The timeout is optional. To not time out use a negative time interval.
 287 * 
 288 * This method will return NO if an error is detected, and set the error pointer (if one was given).
 289 * Possible errors would be a nil host, invalid interface, or socket is already connected.
 290 * 
 291 * If no errors are detected, this method will start a background connect operation and immediately return YES.
 292 * The delegate callbacks are used to notify you when the socket connects, or if the host was unreachable.
 293 * 
 294 * Since this class supports queued reads and writes, you can immediately start reading and/or writing.
 295 * All read/write operations will be queued, and upon socket connection,
 296 * the operations will be dequeued and processed in order.
 297 * 
 298 * The interface may optionally contain a port number at the end of the string, separated by a colon.
 299 * This allows you to specify the local port that should be used for the outgoing connection. (read paragraph to end)
 300 * To specify both interface and local port: "en1:8082" or "192.168.4.35:2424".
 301 * To specify only local port: ":8082".
 302 * Please note this is an advanced feature, and is somewhat hidden on purpose.
 303 * You should understand that 99.999% of the time you should NOT specify the local port for an outgoing connection.
 304 * If you think you need to, there is a very good chance you have a fundamental misunderstanding somewhere.
 305 * Local ports do NOT need to match remote ports. In fact, they almost never do.
 306 * This feature is here for networking professionals using very advanced techniques.
 307**/
 308- (BOOL)connectToAddress:(NSData *)remoteAddr
 309            viaInterface:(NSString *)interface
 310             withTimeout:(NSTimeInterval)timeout
 311                   error:(NSError **)errPtr;
 312
 313#pragma mark Disconnecting
 314
 315/**
 316 * Disconnects immediately (synchronously). Any pending reads or writes are dropped.
 317 * 
 318 * If the socket is not already disconnected, an invocation to the socketDidDisconnect:withError: delegate method
 319 * will be queued onto the delegateQueue asynchronously (behind any previously queued delegate methods).
 320 * In other words, the disconnected delegate method will be invoked sometime shortly after this method returns.
 321 * 
 322 * Please note the recommended way of releasing a GCDAsyncSocket instance (e.g. in a dealloc method)
 323 * [asyncSocket setDelegate:nil];
 324 * [asyncSocket disconnect];
 325 * [asyncSocket release];
 326 * 
 327 * If you plan on disconnecting the socket, and then immediately asking it to connect again,
 328 * you'll likely want to do so like this:
 329 * [asyncSocket setDelegate:nil];
 330 * [asyncSocket disconnect];
 331 * [asyncSocket setDelegate:self];
 332 * [asyncSocket connect...];
 333**/
 334- (void)disconnect;
 335
 336/**
 337 * Disconnects after all pending reads have completed.
 338 * After calling this, the read and write methods will do nothing.
 339 * The socket will disconnect even if there are still pending writes.
 340**/
 341- (void)disconnectAfterReading;
 342
 343/**
 344 * Disconnects after all pending writes have completed.
 345 * After calling this, the read and write methods will do nothing.
 346 * The socket will disconnect even if there are still pending reads.
 347**/
 348- (void)disconnectAfterWriting;
 349
 350/**
 351 * Disconnects after all pending reads and writes have completed.
 352 * After calling this, the read and write methods will do nothing.
 353**/
 354- (void)disconnectAfterReadingAndWriting;
 355
 356#pragma mark Diagnostics
 357
 358/**
 359 * Returns whether the socket is disconnected or connected.
 360 * 
 361 * A disconnected socket may be recycled.
 362 * That is, it can used again for connecting or listening.
 363 * 
 364 * If a socket is in the process of connecting, it may be neither disconnected nor connected.
 365**/
 366- (BOOL)isDisconnected;
 367- (BOOL)isConnected;
 368
 369/**
 370 * Returns the local or remote host and port to which this socket is connected, or nil and 0 if not connected.
 371 * The host will be an IP address.
 372**/
 373- (NSString *)connectedHost;
 374- (uint16_t)connectedPort;
 375
 376- (NSString *)localHost;
 377- (uint16_t)localPort;
 378
 379/**
 380 * Returns the local or remote address to which this socket is connected,
 381 * specified as a sockaddr structure wrapped in a NSData object.
 382 * 
 383 * See also the connectedHost, connectedPort, localHost and localPort methods.
 384**/
 385- (NSData *)connectedAddress;
 386- (NSData *)localAddress;
 387
 388/**
 389 * Returns whether the socket is IPv4 or IPv6.
 390 * An accepting socket may be both.
 391**/
 392- (BOOL)isIPv4;
 393- (BOOL)isIPv6;
 394
 395/**
 396 * Returns whether or not the socket has been secured via SSL/TLS.
 397 * 
 398 * See also the startTLS method.
 399**/
 400- (BOOL)isSecure;
 401
 402#pragma mark Reading
 403
 404// The readData and writeData methods won't block (they are asynchronous).
 405// 
 406// When a read is complete the socket:didReadData:withTag: delegate method is dispatched on the delegateQueue.
 407// When a write is complete the socket:didWriteDataWithTag: delegate method is dispatched on the delegateQueue.
 408// 
 409// You may optionally set a timeout for any read/write operation. (To not timeout, use a negative time interval.)
 410// If a read/write opertion times out, the corresponding "socket:shouldTimeout..." delegate method
 411// is called to optionally allow you to extend the timeout.
 412// Upon a timeout, the "socket:didDisconnectWithError:" method is called
 413// 
 414// The tag is for your convenience.
 415// You can use it as an array index, step number, state id, pointer, etc.
 416
 417/**
 418 * Reads the first available bytes that become available on the socket.
 419 * 
 420 * If the timeout value is negative, the read operation will not use a timeout.
 421**/
 422- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
 423
 424/**
 425 * Reads the first available bytes that become available on the socket.
 426 * The bytes will be appended to the given byte buffer starting at the given offset.
 427 * The given buffer will automatically be increased in size if needed.
 428 * 
 429 * If the timeout value is negative, the read operation will not use a timeout.
 430 * If the buffer if nil, the socket will create a buffer for you.
 431 * 
 432 * If the bufferOffset is greater than the length of the given buffer,
 433 * the method will do nothing, and the delegate will not be called.
 434 * 
 435 * If you pass a buffer, you must not alter it in any way while the socket is using it.
 436 * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
 437 * That is, it will reference the bytes that were appended to the given buffer via
 438 * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
 439**/
 440- (void)readDataWithTimeout:(NSTimeInterval)timeout
 441					 buffer:(NSMutableData *)buffer
 442			   bufferOffset:(NSUInteger)offset
 443						tag:(long)tag;
 444
 445/**
 446 * Reads the first available bytes that become available on the socket.
 447 * The bytes will be appended to the given byte buffer starting at the given offset.
 448 * The given buffer will automatically be increased in size if needed.
 449 * A maximum of length bytes will be read.
 450 * 
 451 * If the timeout value is negative, the read operation will not use a timeout.
 452 * If the buffer if nil, a buffer will automatically be created for you.
 453 * If maxLength is zero, no length restriction is enforced.
 454 * 
 455 * If the bufferOffset is greater than the length of the given buffer,
 456 * the method will do nothing, and the delegate will not be called.
 457 * 
 458 * If you pass a buffer, you must not alter it in any way while the socket is using it.
 459 * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
 460 * That is, it will reference the bytes that were appended to the given buffer  via
 461 * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
 462**/
 463- (void)readDataWithTimeout:(NSTimeInterval)timeout
 464                     buffer:(NSMutableData *)buffer
 465               bufferOffset:(NSUInteger)offset
 466                  maxLength:(NSUInteger)length
 467                        tag:(long)tag;
 468
 469/**
 470 * Reads the given number of bytes.
 471 * 
 472 * If the timeout value is negative, the read operation will not use a timeout.
 473 * 
 474 * If the length is 0, this method does nothing and the delegate is not called.
 475**/
 476- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag;
 477
 478/**
 479 * Reads the given number of bytes.
 480 * The bytes will be appended to the given byte buffer starting at the given offset.
 481 * The given buffer will automatically be increased in size if needed.
 482 * 
 483 * If the timeout value is negative, the read operation will not use a timeout.
 484 * If the buffer if nil, a buffer will automatically be created for you.
 485 * 
 486 * If the length is 0, this method does nothing and the delegate is not called.
 487 * If the bufferOffset is greater than the length of the given buffer,
 488 * the method will do nothing, and the delegate will not be called.
 489 * 
 490 * If you pass a buffer, you must not alter it in any way while AsyncSocket is using it.
 491 * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
 492 * That is, it will reference the bytes that were appended to the given buffer via
 493 * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
 494**/
 495- (void)readDataToLength:(NSUInteger)length
 496             withTimeout:(NSTimeInterval)timeout
 497                  buffer:(NSMutableData *)buffer
 498            bufferOffset:(NSUInteger)offset
 499                     tag:(long)tag;
 500
 501/**
 502 * Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
 503 * 
 504 * If the timeout value is negative, the read operation will not use a timeout.
 505 * 
 506 * If you pass nil or zero-length data as the "data" parameter,
 507 * the method will do nothing (except maybe print a warning), and the delegate will not be called.
 508 * 
 509 * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
 510 * If you're developing your own custom protocol, be sure your separator can not occur naturally as
 511 * part of the data between separators.
 512 * For example, imagine you want to send several small documents over a socket.
 513 * Using CRLF as a separator is likely unwise, as a CRLF could easily exist within the documents.
 514 * In this particular example, it would be better to use a protocol similar to HTTP with
 515 * a header that includes the length of the document.
 516 * Also be careful that your separator cannot occur naturally as part of the encoding for a character.
 517 * 
 518 * The given data (separator) parameter should be immutable.
 519 * For performance reasons, the socket will retain it, not copy it.
 520 * So if it is immutable, don't modify it while the socket is using it.
 521**/
 522- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
 523
 524/**
 525 * Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
 526 * The bytes will be appended to the given byte buffer starting at the given offset.
 527 * The given buffer will automatically be increased in size if needed.
 528 * 
 529 * If the timeout value is negative, the read operation will not use a timeout.
 530 * If the buffer if nil, a buffer will automatically be created for you.
 531 * 
 532 * If the bufferOffset is greater than the length of the given buffer,
 533 * the method will do nothing (except maybe print a warning), and the delegate will not be called.
 534 * 
 535 * If you pass a buffer, you must not alter it in any way while the socket is using it.
 536 * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
 537 * That is, it will reference the bytes that were appended to the given buffer via
 538 * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
 539 * 
 540 * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
 541 * If you're developing your own custom protocol, be sure your separator can not occur naturally as
 542 * part of the data between separators.
 543 * For example, imagine you want to send several small documents over a socket.
 544 * Using CRLF as a separator is likely unwise, as a CRLF could easily exist within the documents.
 545 * In this particular example, it would be better to use a protocol similar to HTTP with
 546 * a header that includes the length of the document.
 547 * Also be careful that your separator cannot occur naturally as part of the encoding for a character.
 548 * 
 549 * The given data (separator) parameter should be immutable.
 550 * For performance reasons, the socket will retain it, not copy it.
 551 * So if it is immutable, don't modify it while the socket is using it.
 552**/
 553- (void)readDataToData:(NSData *)data
 554           withTimeout:(NSTimeInterval)timeout
 555                buffer:(NSMutableData *)buffer
 556          bufferOffset:(NSUInteger)offset
 557                   tag:(long)tag;
 558
 559/**
 560 * Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
 561 * 
 562 * If the timeout value is negative, the read operation will not use a timeout.
 563 * 
 564 * If maxLength is zero, no length restriction is enforced.
 565 * Otherwise if maxLength bytes are read without completing the read,
 566 * it is treated similarly to a timeout - the socket is closed with a GCDAsyncSocketReadMaxedOutError.
 567 * The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.
 568 * 
 569 * If you pass nil or zero-length data as the "data" parameter,
 570 * the method will do nothing (except maybe print a warning), and the delegate will not be called.
 571 * If you pass a maxLength parameter that is less than the length of the data parameter,
 572 * the method will do nothing (except maybe print a warning), and the delegate will not be called.
 573 * 
 574 * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
 575 * If you're developing your own custom protocol, be sure your separator can not occur naturally as
 576 * part of the data between separators.
 577 * For example, imagine you want to send several small documents over a socket.
 578 * Using CRLF as a separator is likely unwise, as a CRLF could easily exist within the documents.
 579 * In this particular example, it would be better to use a protocol similar to HTTP with
 580 * a header that includes the length of the document.
 581 * Also be careful that your separator cannot occur naturally as part of the encoding for a character.
 582 * 
 583 * The given data (separator) parameter should be immutable.
 584 * For performance reasons, the socket will retain it, not copy it.
 585 * So if it is immutable, don't modify it while the socket is using it.
 586**/
 587- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag;
 588
 589/**
 590 * Reads bytes until (and including) the passed "data" parameter, which acts as a separator.
 591 * The bytes will be appended to the given byte buffer starting at the given offset.
 592 * The given buffer will automatically be increased in size if needed.
 593 * 
 594 * If the timeout value is negative, the read operation will not use a timeout.
 595 * If the buffer if nil, a buffer will automatically be created for you.
 596 * 
 597 * If maxLength is zero, no length restriction is enforced.
 598 * Otherwise if maxLength bytes are read without completing the read,
 599 * it is treated similarly to a timeout - the socket is closed with a GCDAsyncSocketReadMaxedOutError.
 600 * The read will complete successfully if exactly maxLength bytes are read and the given data is found at the end.
 601 * 
 602 * If you pass a maxLength parameter that is less than the length of the data (separator) parameter,
 603 * the method will do nothing (except maybe print a warning), and the delegate will not be called.
 604 * If the bufferOffset is greater than the length of the given buffer,
 605 * the method will do nothing (except maybe print a warning), and the delegate will not be called.
 606 * 
 607 * If you pass a buffer, you must not alter it in any way while the socket is using it.
 608 * After completion, the data returned in socket:didReadData:withTag: will be a subset of the given buffer.
 609 * That is, it will reference the bytes that were appended to the given buffer via
 610 * the method [NSData dataWithBytesNoCopy:length:freeWhenDone:NO].
 611 * 
 612 * To read a line from the socket, use the line separator (e.g. CRLF for HTTP, see below) as the "data" parameter.
 613 * If you're developing your own custom protocol, be sure your separator can not occur naturally as
 614 * part of the data between separators.
 615 * For example, imagine you want to send several small documents over a socket.
 616 * Using CRLF as a separator is likely unwise, as a CRLF could easily exist within the documents.
 617 * In this particular example, it would be better to use a protocol similar to HTTP with
 618 * a header that includes the length of the document.
 619 * Also be careful that your separator cannot occur naturally as part of the encoding for a character.
 620 * 
 621 * The given data (separator) parameter should be immutable.
 622 * For performance reasons, the socket will retain it, not copy it.
 623 * So if it is immutable, don't modify it while the socket is using it.
 624**/
 625- (void)readDataToData:(NSData *)data
 626           withTimeout:(NSTimeInterval)timeout
 627                buffer:(NSMutableData *)buffer
 628          bufferOffset:(NSUInteger)offset
 629             maxLength:(NSUInteger)length
 630                   tag:(long)tag;
 631
 632/**
 633 * Returns progress of the current read, from 0.0 to 1.0, or NaN if no current read (use isnan() to check).
 634 * The parameters "tag", "done" and "total" will be filled in if they aren't NULL.
 635**/
 636- (float)progressOfReadReturningTag:(long *)tagPtr bytesDone:(NSUInteger *)donePtr total:(NSUInteger *)totalPtr;
 637
 638#pragma mark Writing
 639
 640/**
 641 * Writes data to the socket, and calls the delegate when finished.
 642 * 
 643 * If you pass in nil or zero-length data, this method does nothing and the delegate will not be called.
 644 * If the timeout value is negative, the write operation will not use a timeout.
 645 * 
 646 * Thread-Safety Note:
 647 * If the given data parameter is mutable (NSMutableData) then you MUST NOT alter the data while
 648 * the socket is writing it. In other words, it's not safe to alter the data until after the delegate method
 649 * socket:didWriteDataWithTag: is invoked signifying that this particular write operation has completed.
 650 * This is due to the fact that GCDAsyncSocket does NOT copy the data. It simply retains it.
 651 * This is for performance reasons. Often times, if NSMutableData is passed, it is because
 652 * a request/response was built up in memory. Copying this data adds an unwanted/unneeded overhead.
 653 * If you need to write data from an immutable buffer, and you need to alter the buffer before the socket
 654 * completes writing the bytes (which is NOT immediately after this method returns, but rather at a later time
 655 * when the delegate method notifies you), then you should first copy the bytes, and pass the copy to this method.
 656**/
 657- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
 658
 659/**
 660 * Returns progress of the current write, from 0.0 to 1.0, or NaN if no current write (use isnan() to check).
 661 * The parameters "tag", "done" and "total" will be filled in if they aren't NULL.
 662**/
 663- (float)progressOfWriteReturningTag:(long *)tagPtr bytesDone:(NSUInteger *)donePtr total:(NSUInteger *)totalPtr;
 664
 665#pragma mark Security
 666
 667/**
 668 * Secures the connection using SSL/TLS.
 669 * 
 670 * This method may be called at any time, and the TLS handshake will occur after all pending reads and writes
 671 * are finished. This allows one the option of sending a protocol dependent StartTLS message, and queuing
 672 * the upgrade to TLS at the same time, without having to wait for the write to finish.
 673 * Any reads or writes scheduled after this method is called will occur over the secured connection.
 674 * 
 675 * The possible keys and values for the TLS settings are well documented.
 676 * Standard keys are:
 677 * 
 678 * - kCFStreamSSLLevel
 679 * - kCFStreamSSLAllowsExpiredCertificates
 680 * - kCFStreamSSLAllowsExpiredRoots
 681 * - kCFStreamSSLAllowsAnyRoot
 682 * - kCFStreamSSLValidatesCertificateChain
 683 * - kCFStreamSSLPeerName
 684 * - kCFStreamSSLCertificates
 685 * - kCFStreamSSLIsServer
 686 * 
 687 * If SecureTransport is available on iOS:
 688 * 
 689 * - GCDAsyncSocketSSLCipherSuites
 690 * - GCDAsyncSocketSSLProtocolVersionMin
 691 * - GCDAsyncSocketSSLProtocolVersionMax
 692 * 
 693 * If SecureTransport is available on Mac OS X:
 694 * 
 695 * - GCDAsyncSocketSSLCipherSuites
 696 * - GCDAsyncSocketSSLDiffieHellmanParameters;
 697 * 
 698 * 
 699 * Please refer to Apple's documentation for associated values, as well as other possible keys.
 700 * 
 701 * If you pass in nil or an empty dictionary, the default settings will be used.
 702 * 
 703 * The default settings will check to make sure the remote party's certificate is signed by a
 704 * trusted 3rd party certificate agency (e.g. verisign) and that the certificate is not expired.
 705 * However it will not verify the name on the certificate unless you
 706 * give it a name to verify against via the kCFStreamSSLPeerName key.
 707 * The security implications of this are important to understand.
 708 * Imagine you are attempting to create a secure connection to MySecureServer.com,
 709 * but your socket gets directed to MaliciousServer.com because of a hacked DNS server.
 710 * If you simply use the default settings, and MaliciousServer.com has a valid certificate,
 711 * the default settings will not detect any problems since the certificate is valid.
 712 * To properly secure your connection in this particular scenario you
 713 * should set the kCFStreamSSLPeerName property to "MySecureServer.com".
 714 * If you do not know the peer name of the remote host in advance (for example, you're not sure
 715 * if it will be "domain.com" or "www.domain.com"), then you can use the default settings to validate the
 716 * certificate, and then use the X509Certificate class to verify the issuer after the socket has been secured.
 717 * The X509Certificate class is part of the CocoaAsyncSocket open source project.
 718 **/
 719- (void)startTLS:(NSDictionary *)tlsSettings;
 720
 721#pragma mark Advanced
 722
 723/**
 724 * Traditionally sockets are not closed until the conversation is over.
 725 * However, it is technically possible for the remote enpoint to close its write stream.
 726 * Our socket would then be notified that there is no more data to be read,
 727 * but our socket would still be writeable and the remote endpoint could continue to receive our data.
 728 * 
 729 * The argument for this confusing functionality stems from the idea that a client could shut down its
 730 * write stream after sending a request to the server, thus notifying the server there are to be no further requests.
 731 * In practice, however, this technique did little to help server developers.
 732 * 
 733 * To make matters worse, from a TCP perspective there is no way to tell the difference from a read stream close
 734 * and a full socket close. They both result in the TCP stack receiving a FIN packet. The only way to tell
 735 * is by continuing to write to the socket. If it was only a read stream close, then writes will continue to work.
 736 * Otherwise an error will be occur shortly (when the remote end sends us a RST packet).
 737 * 
 738 * In addition to the technical challenges and confusion, many high level socket/stream API's provide
 739 * no support for dealing with the problem. If the read stream is closed, the API immediately declares the
 740 * socket to be closed, and shuts down the write stream as well. In fact, this is what Apple's CFStream API does.
 741 * It might sound like poor design at first, but in fact it simplifies development.
 742 * 
 743 * The vast majority of the time if the read stream is closed it's because the remote endpoint closed its socket.
 744 * Thus it actually makes sense to close the socket at this point.
 745 * And in fact this is what most networking developers want and expect to happen.
 746 * However, if you are writing a server that interacts with a plethora of clients,
 747 * you might encounter a client that uses the discouraged technique of shutting down its write stream.
 748 * If this is the case, you can set this property to NO,
 749 * and make use of the socketDidCloseReadStream delegate method.
 750 * 
 751 * The default value is YES.
 752**/
 753- (BOOL)autoDisconnectOnClosedReadStream;
 754- (void)setAutoDisconnectOnClosedReadStream:(BOOL)flag;
 755
 756/**
 757 * GCDAsyncSocket maintains thread safety by using an internal serial dispatch_queue.
 758 * In most cases, the instance creates this queue itself.
 759 * However, to allow for maximum flexibility, the internal queue may be passed in the init method.
 760 * This allows for some advanced options such as controlling socket priority via target queues.
 761 * However, when one begins to use target queues like this, they open the door to some specific deadlock issues.
 762 * 
 763 * For example, imagine there are 2 queues:
 764 * dispatch_queue_t socketQueue;
 765 * dispatch_queue_t socketTargetQueue;
 766 * 
 767 * If you do this (pseudo-code):
 768 * socketQueue.targetQueue = socketTargetQueue;
 769 * 
 770 * Then all socketQueue operations will actually get run on the given socketTargetQueue.
 771 * This is fine and works great in most situations.
 772 * But if you run code directly from within the socketTargetQueue that accesses the socket,
 773 * you could potentially get deadlock. Imagine the following code:
 774 * 
 775 * - (BOOL)socketHasSomething
 776 * {
 777 *     __block BOOL result = NO;
 778 *     dispatch_block_t block = ^{
 779 *         result = [self someInternalMethodToBeRunOnlyOnSocketQueue];
 780 *     }
 781 *     if (is_executing_on_queue(socketQueue))
 782 *         block();
 783 *     else
 784 *         dispatch_sync(socketQueue, block);
 785 *     
 786 *     return result;
 787 * }
 788 * 
 789 * What happens if you call this method from the socketTargetQueue? The result is deadlock.
 790 * This is because the GCD API offers no mechanism to discover a queue's targetQueue.
 791 * Thus we have no idea if our socketQueue is configured with a targetQueue.
 792 * If we had this information, we could easily avoid deadlock.
 793 * But, since these API's are missing or unfeasible, you'll have to explicitly set it.
 794 * 
 795 * IF you pass a socketQueue via the init method,
 796 * AND you've configured the passed socketQueue with a targetQueue,
 797 * THEN you should pass the end queue in the target hierarchy.
 798 * 
 799 * For example, consider the following queue hierarchy:
 800 * socketQueue -> ipQueue -> moduleQueue
 801 *
 802 * This example demonstrates priority shaping within some server.
 803 * All incoming client connections from the same IP address are executed on the same target queue.
 804 * And all connections for a particular module are executed on the same target queue.
 805 * Thus, the priority of all networking for the entire module can be changed on the fly.
 806 * Additionally, networking traffic from a single IP cannot monopolize the module.
 807 * 
 808 * Here's how you would accomplish something like that:
 809 * - (dispatch_queue_t)newSocketQueueForConnectionFromAddress:(NSData *)address onSocket:(GCDAsyncSocket *)sock
 810 * {
 811 *     dispatch_queue_t socketQueue = dispatch_queue_create("", NULL);
 812 *     dispatch_queue_t ipQueue = [self ipQueueForAddress:address];
 813 *     
 814 *     dispatch_set_target_queue(socketQueue, ipQueue);
 815 *     dispatch_set_target_queue(iqQueue, moduleQueue);
 816 *     
 817 *     return socketQueue;
 818 * }
 819 * - (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
 820 * {
 821 *     [clientConnections addObject:newSocket];
 822 *     [newSocket markSocketQueueTargetQueue:moduleQueue];
 823 * }
 824 * 
 825 * Note: This workaround is ONLY needed if you intend to execute code directly on the ipQueue or moduleQueue.
 826 * This is often NOT the case, as such queues are used solely for execution shaping.
 827**/
 828- (void)markSocketQueueTargetQueue:(dispatch_queue_t)socketQueuesPreConfiguredTargetQueue;
 829- (void)unmarkSocketQueueTargetQueue:(dispatch_queue_t)socketQueuesPreviouslyConfiguredTargetQueue;
 830
 831/**
 832 * It's not thread-safe to access certain variables from outside the socket's internal queue.
 833 * 
 834 * For example, the socket file descriptor.
 835 * File descriptors are simply integers which reference an index in the per-process file table.
 836 * However, when one requests a new file descriptor (by opening a file or socket),
 837 * the file descriptor returned is guaranteed to be the lowest numbered unused descriptor.
 838 * So if we're not careful, the following could be possible:
 839 * 
 840 * - Thread A invokes a method which returns the socket's file descriptor.
 841 * - The socket is closed via the socket's internal queue on thread B.
 842 * - Thread C opens a file, and subsequently receives the file descriptor that was previously the socket's FD.
 843 * - Thread A is now accessing/altering the file instead of the socket.
 844 * 
 845 * In addition to this, other variables are not actually objects,
 846 * and thus cannot be retained/released or even autoreleased.
 847 * An example is the sslContext, of type SSLContextRef, which is actually a malloc'd struct.
 848 * 
 849 * Although there are internal variables that make it difficult to maintain thread-safety,
 850 * it is important to provide access to these variables
 851 * to ensure this class can be used in a wide array of environments.
 852 * This method helps to accomplish this by invoking the current block on the socket's internal queue.
 853 * The methods below can be invoked from within the block to access
 854 * those generally thread-unsafe internal variables in a thread-safe manner.
 855 * The given block will be invoked synchronously on the socket's internal queue.
 856 * 
 857 * If you save references to any protected variables and use them outside the block, you do so at your own peril.
 858**/
 859- (void)performBlock:(dispatch_block_t)block;
 860
 861/**
 862 * These methods are only available from within the context of a performBlock: invocation.
 863 * See the documentation for the performBlock: method above.
 864 * 
 865 * Provides access to the socket's file descriptor(s).
 866 * If the socket is a server socket (is accepting incoming connections),
 867 * it might actually have multiple internal socket file descriptors - one for IPv4 and one for IPv6.
 868**/
 869- (int)socketFD;
 870- (int)socket4FD;
 871- (int)socket6FD;
 872
 873#if TARGET_OS_IPHONE
 874
 875/**
 876 * These methods are only available from within the context of a performBlock: invocation.
 877 * See the documentation for the performBlock: method above.
 878 * 
 879 * Provides access to the socket's internal CFReadStream/CFWriteStream.
 880 * 
 881 * These streams are only used as workarounds for specific iOS shortcomings:
 882 * 
 883 * - Apple has decided to keep the SecureTransport framework private is iOS.
 884 *   This means the only supplied way to do SSL/TLS is via CFStream or some other API layered on top of it.
 885 *   Thus, in order to provide SSL/TLS support on iOS we are forced to rely on CFStream,
 886 *   instead of the preferred and faster and more powerful SecureTransport.
 887 * 
 888 * - If a socket doesn't have backgrounding enabled, and that socket is closed while the app is backgrounded,
 889 *   Apple only bothers to notify us via the CFStream API.
 890 *   The faster and more powerful GCD API isn't notified properly in this case.
 891 * 
 892 * See also: (BOOL)enableBackgroundingOnSocket
 893**/
 894- (CFReadStreamRef)readStream;
 895- (CFWriteStreamRef)writeStream;
 896
 897/**
 898 * This method is only available from within the context of a performBlock: invocation.
 899 * See the documentation for the performBlock: method above.
 900 * 
 901 * Configures the socket to allow it to operate when the iOS application has been backgrounded.
 902 * In other words, this method creates a read & write stream, and invokes:
 903 * 
 904 * CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
 905 * CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
 906 * 
 907 * Returns YES if successful, NO otherwise.
 908 * 
 909 * Note: Apple does not officially support backgrounding server sockets.
 910 * That is, if your socket is accepting incoming connections, Apple does not officially support
 911 * allowing iOS applications to accept incoming connections while an app is backgrounded.
 912 * 
 913 * Example usage:
 914 * 
 915 * - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
 916 * {
 917 *     [asyncSocket performBlock:^{
 918 *         [asyncSocket enableBackgroundingOnSocket];
 919 *     }];
 920 * }
 921**/
 922- (BOOL)enableBackgroundingOnSocket;
 923
 924#endif
 925
 926#if SECURE_TRANSPORT_MAYBE_AVAILABLE
 927
 928/**
 929 * This method is only available from within the context of a performBlock: invocation.
 930 * See the documentation for the performBlock: method above.
 931 * 
 932 * Provides access to the socket's SSLContext, if SSL/TLS has been started on the socket.
 933**/
 934- (SSLContextRef)sslContext;
 935
 936#endif
 937
 938#pragma mark Utilities
 939
 940/**
 941 * Extracting host and port information from raw address data.
 942**/
 943+ (NSString *)hostFromAddress:(NSData *)address;
 944+ (uint16_t)portFromAddress:(NSData *)address;
 945+ (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr fromAddress:(NSData *)address;
 946
 947/**
 948 * A few common line separators, for use with the readDataToData:... methods.
 949**/
 950+ (NSData *)CRLFData;   // 0x0D0A
 951+ (NSData *)CRData;     // 0x0D
 952+ (NSData *)LFData;     // 0x0A
 953+ (NSData *)ZeroData;   // 0x00
 954
 955@end
 956
 957////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 958#pragma mark -
 959////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 960
 961@protocol GCDAsyncSocketDelegate
 962@optional
 963
 964/**
 965 * This method is called immediately prior to socket:didAcceptNewSocket:.
 966 * It optionally allows a listening socket to specify the socketQueue for a new accepted socket.
 967 * If this method is not implemented, or returns NULL, the new accepted socket will create its own default queue.
 968 * 
 969 * Since you cannot autorelease a dispatch_queue,
 970 * this method uses the "new" prefix in its name to specify that the returned queue has been retained.
 971 * 
 972 * Thus you could do something like this in the implementation:
 973 * return dispatch_queue_create("MyQueue", NULL);
 974 * 
 975 * If you are placing multiple sockets on the same queue,
 976 * then care should be taken to increment the retain count each time this method is invoked.
 977 * 
 978 * For example, your implementation might look something like this:
 979 * dispatch_retain(myExistingQueue);
 980 * return myExistingQueue;
 981**/
 982- (dispatch_queue_t)newSocketQueueForConnectionFromAddress:(NSData *)address onSocket:(GCDAsyncSocket *)sock;
 983
 984/**
 985 * Called when a socket accepts a connection.
 986 * Another socket is automatically spawned to handle it.
 987 * 
 988 * You must retain the newSocket if you wish to handle the connection.
 989 * Otherwise the newSocket instance will be released and the spawned connection will be closed.
 990 * 
 991 * By default the new socket will have the same delegate and delegateQueue.
 992 * You may, of course, change this at any time.
 993**/
 994- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket;
 995
 996/**
 997 * Called when a socket connects and is ready for reading and writing.
 998 * The host parameter will be an IP address, not a DNS name.
 999**/
1000- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
1001
1002/**
1003 * Called when a socket has completed reading the requested data into memory.
1004 * Not called if there is an error.
1005**/
1006- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
1007
1008/**
1009 * Called when a socket has read in data, but has not yet completed the read.
1010 * This would occur if using readToData: or readToLength: methods.
1011 * It may be used to for things such as updating progress bars.
1012**/
1013- (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
1014
1015/**
1016 * Called when a socket has completed writing the requested data. Not called if there is an error.
1017**/
1018- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag;
1019
1020/**
1021 * Called when a socket has written some data, but has not yet completed the entire write.
1022 * It may be used to for things such as updating progress bars.
1023**/
1024- (void)socket:(GCDAsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
1025
1026/**
1027 * Called if a read operation has reached its timeout without completing.
1028 * This method allows you to optionally extend the timeout.
1029 * If you return a positive time interval (> 0) the read's timeout will be extended by the given amount.
1030 * If you don't implement this method, or return a non-positive time interval (<= 0) the read will timeout as usual.
1031 * 
1032 * The elapsed parameter is the sum of the original timeout, plus any additions previously added via this method.
1033 * The length parameter is the number of bytes that have been read so far for the read operation.
1034 * 
1035 * Note that this method may be called multiple times for a single read if you return positive numbers.
1036**/
1037- (NSTimeInterval)socket:(GCDAsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag
1038                                                                 elapsed:(NSTimeInterval)elapsed
1039                                                               bytesDone:(NSUInteger)length;
1040
1041/**
1042 * Called if a write operation has reached its timeout without completing.
1043 * This method allows you to optionally extend the timeout.
1044 * If you return a positive time interval (> 0) the write's timeout will be extended by the given amount.
1045 * If you don't implement this method, or return a non-positive time interval (<= 0) the write will timeout as usual.
1046 * 
1047 * The elapsed parameter is the sum of the original timeout, plus any additions previously added via this method.
1048 * The length parameter is the number of bytes that have been written so far for the write operation.
1049 * 
1050 * Note that this method may be called multiple times for a single write if you return positive numbers.
1051**/
1052- (NSTimeInterval)socket:(GCDAsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag
1053                                                                  elapsed:(NSTimeInterval)elapsed
1054                                                                bytesDone:(NSUInteger)length;
1055
1056/**
1057 * Conditionally called if the read stream closes, but the write stream may still be writeable.
1058 * 
1059 * This delegate method is only called if autoDisconnectOnClosedReadStream has been set to NO.
1060 * See the discussion on the autoDisconnectOnClosedReadStream method for more information.
1061**/
1062- (void)socketDidCloseReadStream:(GCDAsyncSocket *)sock;
1063
1064/**
1065 * Called when a socket disconnects with or without erro…

Large files files are truncated, but you can click here to view the full file