PageRenderTime 65ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/GCDAsyncSocket.h

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

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