PageRenderTime 62ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/Pods/CocoaAsyncSocket/GCD/GCDAsyncSocket.h

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