PageRenderTime 62ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

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

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