PageRenderTime 39ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/Vendor/AsyncSocket/GCDAsyncUdpSocket.h

https://github.com/spark/ios-app
C Header | 994 lines | 135 code | 80 blank | 779 comment | 0 complexity | cb5e687312f2c773aa1a11c4ced7a28f MD5 | raw file
  1. //
  2. // GCDAsyncUdpSocket
  3. //
  4. // This class is in the public domain.
  5. // Originally created by Robbie Hanson of Deusty LLC.
  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 <dispatch/dispatch.h>
  12. extern NSString *const GCDAsyncUdpSocketException;
  13. extern NSString *const GCDAsyncUdpSocketErrorDomain;
  14. extern NSString *const GCDAsyncUdpSocketQueueName;
  15. extern NSString *const GCDAsyncUdpSocketThreadName;
  16. enum GCDAsyncUdpSocketError
  17. {
  18. GCDAsyncUdpSocketNoError = 0, // Never used
  19. GCDAsyncUdpSocketBadConfigError, // Invalid configuration
  20. GCDAsyncUdpSocketBadParamError, // Invalid parameter was passed
  21. GCDAsyncUdpSocketSendTimeoutError, // A send operation timed out
  22. GCDAsyncUdpSocketClosedError, // The socket was closed
  23. GCDAsyncUdpSocketOtherError, // Description provided in userInfo
  24. };
  25. typedef enum GCDAsyncUdpSocketError GCDAsyncUdpSocketError;
  26. /**
  27. * You may optionally set a receive filter for the socket.
  28. * A filter can provide several useful features:
  29. *
  30. * 1. Many times udp packets need to be parsed.
  31. * Since the filter can run in its own independent queue, you can parallelize this parsing quite easily.
  32. * The end result is a parallel socket io, datagram parsing, and packet processing.
  33. *
  34. * 2. Many times udp packets are discarded because they are duplicate/unneeded/unsolicited.
  35. * The filter can prevent such packets from arriving at the delegate.
  36. * And because the filter can run in its own independent queue, this doesn't slow down the delegate.
  37. *
  38. * - Since the udp protocol does not guarantee delivery, udp packets may be lost.
  39. * Many protocols built atop udp thus provide various resend/re-request algorithms.
  40. * This sometimes results in duplicate packets arriving.
  41. * A filter may allow you to architect the duplicate detection code to run in parallel to normal processing.
  42. *
  43. * - Since the udp socket may be connectionless, its possible for unsolicited packets to arrive.
  44. * Such packets need to be ignored.
  45. *
  46. * 3. Sometimes traffic shapers are needed to simulate real world environments.
  47. * A filter allows you to write custom code to simulate such environments.
  48. * The ability to code this yourself is especially helpful when your simulated environment
  49. * is more complicated than simple traffic shaping (e.g. simulating a cone port restricted router),
  50. * or the system tools to handle this aren't available (e.g. on a mobile device).
  51. *
  52. * @param data - The packet that was received.
  53. * @param address - The address the data was received from.
  54. * See utilities section for methods to extract info from address.
  55. * @param context - Out parameter you may optionally set, which will then be passed to the delegate method.
  56. * For example, filter block can parse the data and then,
  57. * pass the parsed data to the delegate.
  58. *
  59. * @returns - YES if the received packet should be passed onto the delegate.
  60. * NO if the received packet should be discarded, and not reported to the delegete.
  61. *
  62. * Example:
  63. *
  64. * GCDAsyncUdpSocketReceiveFilterBlock filter = ^BOOL (NSData *data, NSData *address, id *context) {
  65. *
  66. * MyProtocolMessage *msg = [MyProtocol parseMessage:data];
  67. *
  68. * *context = response;
  69. * return (response != nil);
  70. * };
  71. * [udpSocket setReceiveFilter:filter withQueue:myParsingQueue];
  72. *
  73. **/
  74. typedef BOOL (^GCDAsyncUdpSocketReceiveFilterBlock)(NSData *data, NSData *address, id *context);
  75. /**
  76. * You may optionally set a send filter for the socket.
  77. * A filter can provide several interesting possibilities:
  78. *
  79. * 1. Optional caching of resolved addresses for domain names.
  80. * The cache could later be consulted, resulting in fewer system calls to getaddrinfo.
  81. *
  82. * 2. Reusable modules of code for bandwidth monitoring.
  83. *
  84. * 3. Sometimes traffic shapers are needed to simulate real world environments.
  85. * A filter allows you to write custom code to simulate such environments.
  86. * The ability to code this yourself is especially helpful when your simulated environment
  87. * is more complicated than simple traffic shaping (e.g. simulating a cone port restricted router),
  88. * or the system tools to handle this aren't available (e.g. on a mobile device).
  89. *
  90. * @param data - The packet that was received.
  91. * @param address - The address the data was received from.
  92. * See utilities section for methods to extract info from address.
  93. * @param tag - The tag that was passed in the send method.
  94. *
  95. * @returns - YES if the packet should actually be sent over the socket.
  96. * NO if the packet should be silently dropped (not sent over the socket).
  97. *
  98. * Regardless of the return value, the delegate will be informed that the packet was successfully sent.
  99. *
  100. **/
  101. typedef BOOL (^GCDAsyncUdpSocketSendFilterBlock)(NSData *data, NSData *address, long tag);
  102. @interface GCDAsyncUdpSocket : NSObject
  103. /**
  104. * GCDAsyncUdpSocket uses the standard delegate paradigm,
  105. * but executes all delegate callbacks on a given delegate dispatch queue.
  106. * This allows for maximum concurrency, while at the same time providing easy thread safety.
  107. *
  108. * You MUST set a delegate AND delegate dispatch queue before attempting to
  109. * use the socket, or you will get an error.
  110. *
  111. * The socket queue is optional.
  112. * If you pass NULL, GCDAsyncSocket will automatically create its own socket queue.
  113. * If you choose to provide a socket queue, the socket queue must not be a concurrent queue,
  114. * then please see the discussion for the method markSocketQueueTargetQueue.
  115. *
  116. * The delegate queue and socket queue can optionally be the same.
  117. **/
  118. - (id)init;
  119. - (id)initWithSocketQueue:(dispatch_queue_t)sq;
  120. - (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq;
  121. - (id)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq;
  122. #pragma mark Configuration
  123. - (id)delegate;
  124. - (void)setDelegate:(id)delegate;
  125. - (void)synchronouslySetDelegate:(id)delegate;
  126. - (dispatch_queue_t)delegateQueue;
  127. - (void)setDelegateQueue:(dispatch_queue_t)delegateQueue;
  128. - (void)synchronouslySetDelegateQueue:(dispatch_queue_t)delegateQueue;
  129. - (void)getDelegate:(id *)delegatePtr delegateQueue:(dispatch_queue_t *)delegateQueuePtr;
  130. - (void)setDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
  131. - (void)synchronouslySetDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
  132. /**
  133. * By default, both IPv4 and IPv6 are enabled.
  134. *
  135. * This means GCDAsyncUdpSocket automatically supports both protocols,
  136. * and can send to IPv4 or IPv6 addresses,
  137. * as well as receive over IPv4 and IPv6.
  138. *
  139. * For operations that require DNS resolution, GCDAsyncUdpSocket supports both IPv4 and IPv6.
  140. * If a DNS lookup returns only IPv4 results, GCDAsyncUdpSocket will automatically use IPv4.
  141. * If a DNS lookup returns only IPv6 results, GCDAsyncUdpSocket will automatically use IPv6.
  142. * If a DNS lookup returns both IPv4 and IPv6 results, then the protocol used depends on the configured preference.
  143. * If IPv4 is preferred, then IPv4 is used.
  144. * If IPv6 is preferred, then IPv6 is used.
  145. * If neutral, then the first IP version in the resolved array will be used.
  146. *
  147. * Starting with Mac OS X 10.7 Lion and iOS 5, the default IP preference is neutral.
  148. * On prior systems the default IP preference is IPv4.
  149. **/
  150. - (BOOL)isIPv4Enabled;
  151. - (void)setIPv4Enabled:(BOOL)flag;
  152. - (BOOL)isIPv6Enabled;
  153. - (void)setIPv6Enabled:(BOOL)flag;
  154. - (BOOL)isIPv4Preferred;
  155. - (BOOL)isIPv6Preferred;
  156. - (BOOL)isIPVersionNeutral;
  157. - (void)setPreferIPv4;
  158. - (void)setPreferIPv6;
  159. - (void)setIPVersionNeutral;
  160. /**
  161. * Gets/Sets the maximum size of the buffer that will be allocated for receive operations.
  162. * The default maximum size is 9216 bytes.
  163. *
  164. * The theoretical maximum size of any IPv4 UDP packet is UINT16_MAX = 65535.
  165. * The theoretical maximum size of any IPv6 UDP packet is UINT32_MAX = 4294967295.
  166. *
  167. * Since the OS/GCD notifies us of the size of each received UDP packet,
  168. * the actual allocated buffer size for each packet is exact.
  169. * And in practice the size of UDP packets is generally much smaller than the max.
  170. * Indeed most protocols will send and receive packets of only a few bytes,
  171. * or will set a limit on the size of packets to prevent fragmentation in the IP layer.
  172. *
  173. * If you set the buffer size too small, the sockets API in the OS will silently discard
  174. * any extra data, and you will not be notified of the error.
  175. **/
  176. - (uint16_t)maxReceiveIPv4BufferSize;
  177. - (void)setMaxReceiveIPv4BufferSize:(uint16_t)max;
  178. - (uint32_t)maxReceiveIPv6BufferSize;
  179. - (void)setMaxReceiveIPv6BufferSize:(uint32_t)max;
  180. /**
  181. * User data allows you to associate arbitrary information with the socket.
  182. * This data is not used internally in any way.
  183. **/
  184. - (id)userData;
  185. - (void)setUserData:(id)arbitraryUserData;
  186. #pragma mark Diagnostics
  187. /**
  188. * Returns the local address info for the socket.
  189. *
  190. * The localAddress method returns a sockaddr structure wrapped in a NSData object.
  191. * The localHost method returns the human readable IP address as a string.
  192. *
  193. * Note: Address info may not be available until after the socket has been binded, connected
  194. * or until after data has been sent.
  195. **/
  196. - (NSData *)localAddress;
  197. - (NSString *)localHost;
  198. - (uint16_t)localPort;
  199. - (NSData *)localAddress_IPv4;
  200. - (NSString *)localHost_IPv4;
  201. - (uint16_t)localPort_IPv4;
  202. - (NSData *)localAddress_IPv6;
  203. - (NSString *)localHost_IPv6;
  204. - (uint16_t)localPort_IPv6;
  205. /**
  206. * Returns the remote address info for the socket.
  207. *
  208. * The connectedAddress method returns a sockaddr structure wrapped in a NSData object.
  209. * The connectedHost method returns the human readable IP address as a string.
  210. *
  211. * Note: Since UDP is connectionless by design, connected address info
  212. * will not be available unless the socket is explicitly connected to a remote host/port.
  213. * If the socket is not connected, these methods will return nil / 0.
  214. **/
  215. - (NSData *)connectedAddress;
  216. - (NSString *)connectedHost;
  217. - (uint16_t)connectedPort;
  218. /**
  219. * Returns whether or not this socket has been connected to a single host.
  220. * By design, UDP is a connectionless protocol, and connecting is not needed.
  221. * If connected, the socket will only be able to send/receive data to/from the connected host.
  222. **/
  223. - (BOOL)isConnected;
  224. /**
  225. * Returns whether or not this socket has been closed.
  226. * The only way a socket can be closed is if you explicitly call one of the close methods.
  227. **/
  228. - (BOOL)isClosed;
  229. /**
  230. * Returns whether or not this socket is IPv4.
  231. *
  232. * By default this will be true, unless:
  233. * - IPv4 is disabled (via setIPv4Enabled:)
  234. * - The socket is explicitly bound to an IPv6 address
  235. * - The socket is connected to an IPv6 address
  236. **/
  237. - (BOOL)isIPv4;
  238. /**
  239. * Returns whether or not this socket is IPv6.
  240. *
  241. * By default this will be true, unless:
  242. * - IPv6 is disabled (via setIPv6Enabled:)
  243. * - The socket is explicitly bound to an IPv4 address
  244. * _ The socket is connected to an IPv4 address
  245. *
  246. * This method will also return false on platforms that do not support IPv6.
  247. * Note: The iPhone does not currently support IPv6.
  248. **/
  249. - (BOOL)isIPv6;
  250. #pragma mark Binding
  251. /**
  252. * Binds the UDP socket to the given port.
  253. * Binding should be done for server sockets that receive data prior to sending it.
  254. * Client sockets can skip binding,
  255. * as the OS will automatically assign the socket an available port when it starts sending data.
  256. *
  257. * You may optionally pass a port number of zero to immediately bind the socket,
  258. * yet still allow the OS to automatically assign an available port.
  259. *
  260. * You cannot bind a socket after its been connected.
  261. * You can only bind a socket once.
  262. * You can still connect a socket (if desired) after binding.
  263. *
  264. * On success, returns YES.
  265. * Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass NULL for errPtr.
  266. **/
  267. - (BOOL)bindToPort:(uint16_t)port error:(NSError **)errPtr;
  268. /**
  269. * Binds the UDP socket to the given port and optional interface.
  270. * Binding should be done for server sockets that receive data prior to sending it.
  271. * Client sockets can skip binding,
  272. * as the OS will automatically assign the socket an available port when it starts sending data.
  273. *
  274. * You may optionally pass a port number of zero to immediately bind the socket,
  275. * yet still allow the OS to automatically assign an available port.
  276. *
  277. * The interface may be a name (e.g. "en1" or "lo0") or the corresponding IP address (e.g. "192.168.4.35").
  278. * You may also use the special strings "localhost" or "loopback" to specify that
  279. * the socket only accept packets from the local machine.
  280. *
  281. * You cannot bind a socket after its been connected.
  282. * You can only bind a socket once.
  283. * You can still connect a socket (if desired) after binding.
  284. *
  285. * On success, returns YES.
  286. * Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass NULL for errPtr.
  287. **/
  288. - (BOOL)bindToPort:(uint16_t)port interface:(NSString *)interface error:(NSError **)errPtr;
  289. /**
  290. * Binds the UDP socket to the given address, specified as a sockaddr structure wrapped in a NSData object.
  291. *
  292. * If you have an existing struct sockaddr you can convert it to a NSData object like so:
  293. * struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
  294. * struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
  295. *
  296. * Binding should be done for server sockets that receive data prior to sending it.
  297. * Client sockets can skip binding,
  298. * as the OS will automatically assign the socket an available port when it starts sending data.
  299. *
  300. * You cannot bind a socket after its been connected.
  301. * You can only bind a socket once.
  302. * You can still connect a socket (if desired) after binding.
  303. *
  304. * On success, returns YES.
  305. * Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass NULL for errPtr.
  306. **/
  307. - (BOOL)bindToAddress:(NSData *)localAddr error:(NSError **)errPtr;
  308. #pragma mark Connecting
  309. /**
  310. * Connects the UDP socket to the given host and port.
  311. * By design, UDP is a connectionless protocol, and connecting is not needed.
  312. *
  313. * Choosing to connect to a specific host/port has the following effect:
  314. * - You will only be able to send data to the connected host/port.
  315. * - You will only be able to receive data from the connected host/port.
  316. * - You will receive ICMP messages that come from the connected host/port, such as "connection refused".
  317. *
  318. * The actual process of connecting a UDP socket does not result in any communication on the socket.
  319. * It simply changes the internal state of the socket.
  320. *
  321. * You cannot bind a socket after it has been connected.
  322. * You can only connect a socket once.
  323. *
  324. * The host may be a domain name (e.g. "deusty.com") or an IP address string (e.g. "192.168.0.2").
  325. *
  326. * This method is asynchronous as it requires a DNS lookup to resolve the given host name.
  327. * If an obvious error is detected, this method immediately returns NO and sets errPtr.
  328. * If you don't care about the error, you can pass nil for errPtr.
  329. * Otherwise, this method returns YES and begins the asynchronous connection process.
  330. * The result of the asynchronous connection process will be reported via the delegate methods.
  331. **/
  332. - (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)errPtr;
  333. /**
  334. * Connects the UDP socket to the given address, specified as a sockaddr structure wrapped in a NSData object.
  335. *
  336. * If you have an existing struct sockaddr you can convert it to a NSData object like so:
  337. * struct sockaddr sa -> NSData *dsa = [NSData dataWithBytes:&remoteAddr length:remoteAddr.sa_len];
  338. * struct sockaddr *sa -> NSData *dsa = [NSData dataWithBytes:remoteAddr length:remoteAddr->sa_len];
  339. *
  340. * By design, UDP is a connectionless protocol, and connecting is not needed.
  341. *
  342. * Choosing to connect to a specific address has the following effect:
  343. * - You will only be able to send data to the connected address.
  344. * - You will only be able to receive data from the connected address.
  345. * - You will receive ICMP messages that come from the connected address, such as "connection refused".
  346. *
  347. * Connecting a UDP socket does not result in any communication on the socket.
  348. * It simply changes the internal state of the socket.
  349. *
  350. * You cannot bind a socket after its been connected.
  351. * You can only connect a socket once.
  352. *
  353. * On success, returns YES.
  354. * Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
  355. *
  356. * Note: Unlike the connectToHost:onPort:error: method, this method does not require a DNS lookup.
  357. * Thus when this method returns, the connection has either failed or fully completed.
  358. * In other words, this method is synchronous, unlike the asynchronous connectToHost::: method.
  359. * However, for compatibility and simplification of delegate code, if this method returns YES
  360. * then the corresponding delegate method (udpSocket:didConnectToHost:port:) is still invoked.
  361. **/
  362. - (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr;
  363. #pragma mark Multicast
  364. /**
  365. * Join multicast group.
  366. * Group should be an IP address (eg @"225.228.0.1").
  367. *
  368. * On success, returns YES.
  369. * Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
  370. **/
  371. - (BOOL)joinMulticastGroup:(NSString *)group error:(NSError **)errPtr;
  372. /**
  373. * Join multicast group.
  374. * Group should be an IP address (eg @"225.228.0.1").
  375. * The interface may be a name (e.g. "en1" or "lo0") or the corresponding IP address (e.g. "192.168.4.35").
  376. *
  377. * On success, returns YES.
  378. * Otherwise returns NO, and sets errPtr. If you don't care about the error, you can pass nil for errPtr.
  379. **/
  380. - (BOOL)joinMulticastGroup:(NSString *)group onInterface:(NSString *)interface error:(NSError **)errPtr;
  381. - (BOOL)leaveMulticastGroup:(NSString *)group error:(NSError **)errPtr;
  382. - (BOOL)leaveMulticastGroup:(NSString *)group onInterface:(NSString *)interface error:(NSError **)errPtr;
  383. #pragma mark Broadcast
  384. /**
  385. * By default, the underlying socket in the OS will not allow you to send broadcast messages.
  386. * In order to send broadcast messages, you need to enable this functionality in the socket.
  387. *
  388. * A broadcast is a UDP message to addresses like "192.168.255.255" or "255.255.255.255" that is
  389. * delivered to every host on the network.
  390. * The reason this is generally disabled by default (by the OS) is to prevent
  391. * accidental broadcast messages from flooding the network.
  392. **/
  393. - (BOOL)enableBroadcast:(BOOL)flag error:(NSError **)errPtr;
  394. #pragma mark Sending
  395. /**
  396. * Asynchronously sends the given data, with the given timeout and tag.
  397. *
  398. * This method may only be used with a connected socket.
  399. * Recall that connecting is optional for a UDP socket.
  400. * For connected sockets, data can only be sent to the connected address.
  401. * For non-connected sockets, the remote destination is specified for each packet.
  402. * For more information about optionally connecting udp sockets, see the documentation for the connect methods above.
  403. *
  404. * @param data
  405. * The data to send.
  406. * If data is nil or zero-length, this method does nothing.
  407. * If passing NSMutableData, please read the thread-safety notice below.
  408. *
  409. * @param timeout
  410. * The timeout for the send opeartion.
  411. * If the timeout value is negative, the send operation will not use a timeout.
  412. *
  413. * @param tag
  414. * The tag is for your convenience.
  415. * It is not sent or received over the socket in any manner what-so-ever.
  416. * It is reported back as a parameter in the udpSocket:didSendDataWithTag:
  417. * or udpSocket:didNotSendDataWithTag:dueToError: methods.
  418. * You can use it as an array index, state id, type constant, etc.
  419. *
  420. *
  421. * Thread-Safety Note:
  422. * If the given data parameter is mutable (NSMutableData) then you MUST NOT alter the data while
  423. * the socket is sending it. In other words, it's not safe to alter the data until after the delegate method
  424. * udpSocket:didSendDataWithTag: or udpSocket:didNotSendDataWithTag:dueToError: is invoked signifying
  425. * that this particular send operation has completed.
  426. * This is due to the fact that GCDAsyncUdpSocket does NOT copy the data.
  427. * It simply retains it for performance reasons.
  428. * Often times, if NSMutableData is passed, it is because a request/response was built up in memory.
  429. * Copying this data adds an unwanted/unneeded overhead.
  430. * If you need to write data from an immutable buffer, and you need to alter the buffer before the socket
  431. * completes sending the bytes (which is NOT immediately after this method returns, but rather at a later time
  432. * when the delegate method notifies you), then you should first copy the bytes, and pass the copy to this method.
  433. **/
  434. - (void)sendData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
  435. /**
  436. * Asynchronously sends the given data, with the given timeout and tag, to the given host and port.
  437. *
  438. * This method cannot be used with a connected socket.
  439. * Recall that connecting is optional for a UDP socket.
  440. * For connected sockets, data can only be sent to the connected address.
  441. * For non-connected sockets, the remote destination is specified for each packet.
  442. * For more information about optionally connecting udp sockets, see the documentation for the connect methods above.
  443. *
  444. * @param data
  445. * The data to send.
  446. * If data is nil or zero-length, this method does nothing.
  447. * If passing NSMutableData, please read the thread-safety notice below.
  448. *
  449. * @param host
  450. * The destination to send the udp packet to.
  451. * May be specified as a domain name (e.g. "deusty.com") or an IP address string (e.g. "192.168.0.2").
  452. * You may also use the convenience strings of "loopback" or "localhost".
  453. *
  454. * @param port
  455. * The port of the host to send to.
  456. *
  457. * @param timeout
  458. * The timeout for the send opeartion.
  459. * If the timeout value is negative, the send operation will not use a timeout.
  460. *
  461. * @param tag
  462. * The tag is for your convenience.
  463. * It is not sent or received over the socket in any manner what-so-ever.
  464. * It is reported back as a parameter in the udpSocket:didSendDataWithTag:
  465. * or udpSocket:didNotSendDataWithTag:dueToError: methods.
  466. * You can use it as an array index, state id, type constant, etc.
  467. *
  468. *
  469. * Thread-Safety Note:
  470. * If the given data parameter is mutable (NSMutableData) then you MUST NOT alter the data while
  471. * the socket is sending it. In other words, it's not safe to alter the data until after the delegate method
  472. * udpSocket:didSendDataWithTag: or udpSocket:didNotSendDataWithTag:dueToError: is invoked signifying
  473. * that this particular send operation has completed.
  474. * This is due to the fact that GCDAsyncUdpSocket does NOT copy the data.
  475. * It simply retains it for performance reasons.
  476. * Often times, if NSMutableData is passed, it is because a request/response was built up in memory.
  477. * Copying this data adds an unwanted/unneeded overhead.
  478. * If you need to write data from an immutable buffer, and you need to alter the buffer before the socket
  479. * completes sending the bytes (which is NOT immediately after this method returns, but rather at a later time
  480. * when the delegate method notifies you), then you should first copy the bytes, and pass the copy to this method.
  481. **/
  482. - (void)sendData:(NSData *)data
  483. toHost:(NSString *)host
  484. port:(uint16_t)port
  485. withTimeout:(NSTimeInterval)timeout
  486. tag:(long)tag;
  487. /**
  488. * Asynchronously sends the given data, with the given timeout and tag, to the given address.
  489. *
  490. * This method cannot be used with a connected socket.
  491. * Recall that connecting is optional for a UDP socket.
  492. * For connected sockets, data can only be sent to the connected address.
  493. * For non-connected sockets, the remote destination is specified for each packet.
  494. * For more information about optionally connecting udp sockets, see the documentation for the connect methods above.
  495. *
  496. * @param data
  497. * The data to send.
  498. * If data is nil or zero-length, this method does nothing.
  499. * If passing NSMutableData, please read the thread-safety notice below.
  500. *
  501. * @param address
  502. * The address to send the data to (specified as a sockaddr structure wrapped in a NSData object).
  503. *
  504. * @param timeout
  505. * The timeout for the send opeartion.
  506. * If the timeout value is negative, the send operation will not use a timeout.
  507. *
  508. * @param tag
  509. * The tag is for your convenience.
  510. * It is not sent or received over the socket in any manner what-so-ever.
  511. * It is reported back as a parameter in the udpSocket:didSendDataWithTag:
  512. * or udpSocket:didNotSendDataWithTag:dueToError: methods.
  513. * You can use it as an array index, state id, type constant, etc.
  514. *
  515. *
  516. * Thread-Safety Note:
  517. * If the given data parameter is mutable (NSMutableData) then you MUST NOT alter the data while
  518. * the socket is sending it. In other words, it's not safe to alter the data until after the delegate method
  519. * udpSocket:didSendDataWithTag: or udpSocket:didNotSendDataWithTag:dueToError: is invoked signifying
  520. * that this particular send operation has completed.
  521. * This is due to the fact that GCDAsyncUdpSocket does NOT copy the data.
  522. * It simply retains it for performance reasons.
  523. * Often times, if NSMutableData is passed, it is because a request/response was built up in memory.
  524. * Copying this data adds an unwanted/unneeded overhead.
  525. * If you need to write data from an immutable buffer, and you need to alter the buffer before the socket
  526. * completes sending the bytes (which is NOT immediately after this method returns, but rather at a later time
  527. * when the delegate method notifies you), then you should first copy the bytes, and pass the copy to this method.
  528. **/
  529. - (void)sendData:(NSData *)data toAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout tag:(long)tag;
  530. /**
  531. * You may optionally set a send filter for the socket.
  532. * A filter can provide several interesting possibilities:
  533. *
  534. * 1. Optional caching of resolved addresses for domain names.
  535. * The cache could later be consulted, resulting in fewer system calls to getaddrinfo.
  536. *
  537. * 2. Reusable modules of code for bandwidth monitoring.
  538. *
  539. * 3. Sometimes traffic shapers are needed to simulate real world environments.
  540. * A filter allows you to write custom code to simulate such environments.
  541. * The ability to code this yourself is especially helpful when your simulated environment
  542. * is more complicated than simple traffic shaping (e.g. simulating a cone port restricted router),
  543. * or the system tools to handle this aren't available (e.g. on a mobile device).
  544. *
  545. * For more information about GCDAsyncUdpSocketSendFilterBlock, see the documentation for its typedef.
  546. * To remove a previously set filter, invoke this method and pass a nil filterBlock and NULL filterQueue.
  547. *
  548. * Note: This method invokes setSendFilter:withQueue:isAsynchronous: (documented below),
  549. * passing YES for the isAsynchronous parameter.
  550. **/
  551. - (void)setSendFilter:(GCDAsyncUdpSocketSendFilterBlock)filterBlock withQueue:(dispatch_queue_t)filterQueue;
  552. /**
  553. * The receive filter can be run via dispatch_async or dispatch_sync.
  554. * Most typical situations call for asynchronous operation.
  555. *
  556. * However, there are a few situations in which synchronous operation is preferred.
  557. * Such is the case when the filter is extremely minimal and fast.
  558. * This is because dispatch_sync is faster than dispatch_async.
  559. *
  560. * If you choose synchronous operation, be aware of possible deadlock conditions.
  561. * Since the socket queue is executing your block via dispatch_sync,
  562. * then you cannot perform any tasks which may invoke dispatch_sync on the socket queue.
  563. * For example, you can't query properties on the socket.
  564. **/
  565. - (void)setSendFilter:(GCDAsyncUdpSocketSendFilterBlock)filterBlock
  566. withQueue:(dispatch_queue_t)filterQueue
  567. isAsynchronous:(BOOL)isAsynchronous;
  568. #pragma mark Receiving
  569. /**
  570. * There are two modes of operation for receiving packets: one-at-a-time & continuous.
  571. *
  572. * In one-at-a-time mode, you call receiveOnce everytime your delegate is ready to process an incoming udp packet.
  573. * Receiving packets one-at-a-time may be better suited for implementing certain state machine code,
  574. * where your state machine may not always be ready to process incoming packets.
  575. *
  576. * In continuous mode, the delegate is invoked immediately everytime incoming udp packets are received.
  577. * Receiving packets continuously is better suited to real-time streaming applications.
  578. *
  579. * You may switch back and forth between one-at-a-time mode and continuous mode.
  580. * If the socket is currently in continuous mode, calling this method will switch it to one-at-a-time mode.
  581. *
  582. * When a packet is received (and not filtered by the optional receive filter),
  583. * the delegate method (udpSocket:didReceiveData:fromAddress:withFilterContext:) is invoked.
  584. *
  585. * If the socket is able to begin receiving packets, this method returns YES.
  586. * Otherwise it returns NO, and sets the errPtr with appropriate error information.
  587. *
  588. * An example error:
  589. * You created a udp socket to act as a server, and immediately called receive.
  590. * You forgot to first bind the socket to a port number, and received a error with a message like:
  591. * "Must bind socket before you can receive data."
  592. **/
  593. - (BOOL)receiveOnce:(NSError **)errPtr;
  594. /**
  595. * There are two modes of operation for receiving packets: one-at-a-time & continuous.
  596. *
  597. * In one-at-a-time mode, you call receiveOnce everytime your delegate is ready to process an incoming udp packet.
  598. * Receiving packets one-at-a-time may be better suited for implementing certain state machine code,
  599. * where your state machine may not always be ready to process incoming packets.
  600. *
  601. * In continuous mode, the delegate is invoked immediately everytime incoming udp packets are received.
  602. * Receiving packets continuously is better suited to real-time streaming applications.
  603. *
  604. * You may switch back and forth between one-at-a-time mode and continuous mode.
  605. * If the socket is currently in one-at-a-time mode, calling this method will switch it to continuous mode.
  606. *
  607. * For every received packet (not filtered by the optional receive filter),
  608. * the delegate method (udpSocket:didReceiveData:fromAddress:withFilterContext:) is invoked.
  609. *
  610. * If the socket is able to begin receiving packets, this method returns YES.
  611. * Otherwise it returns NO, and sets the errPtr with appropriate error information.
  612. *
  613. * An example error:
  614. * You created a udp socket to act as a server, and immediately called receive.
  615. * You forgot to first bind the socket to a port number, and received a error with a message like:
  616. * "Must bind socket before you can receive data."
  617. **/
  618. - (BOOL)beginReceiving:(NSError **)errPtr;
  619. /**
  620. * If the socket is currently receiving (beginReceiving has been called), this method pauses the receiving.
  621. * That is, it won't read any more packets from the underlying OS socket until beginReceiving is called again.
  622. *
  623. * Important Note:
  624. * GCDAsyncUdpSocket may be running in parallel with your code.
  625. * That is, your delegate is likely running on a separate thread/dispatch_queue.
  626. * When you invoke this method, GCDAsyncUdpSocket may have already dispatched delegate methods to be invoked.
  627. * Thus, if those delegate methods have already been dispatch_async'd,
  628. * your didReceive delegate method may still be invoked after this method has been called.
  629. * You should be aware of this, and program defensively.
  630. **/
  631. - (void)pauseReceiving;
  632. /**
  633. * You may optionally set a receive filter for the socket.
  634. * This receive filter may be set to run in its own queue (independent of delegate queue).
  635. *
  636. * A filter can provide several useful features.
  637. *
  638. * 1. Many times udp packets need to be parsed.
  639. * Since the filter can run in its own independent queue, you can parallelize this parsing quite easily.
  640. * The end result is a parallel socket io, datagram parsing, and packet processing.
  641. *
  642. * 2. Many times udp packets are discarded because they are duplicate/unneeded/unsolicited.
  643. * The filter can prevent such packets from arriving at the delegate.
  644. * And because the filter can run in its own independent queue, this doesn't slow down the delegate.
  645. *
  646. * - Since the udp protocol does not guarantee delivery, udp packets may be lost.
  647. * Many protocols built atop udp thus provide various resend/re-request algorithms.
  648. * This sometimes results in duplicate packets arriving.
  649. * A filter may allow you to architect the duplicate detection code to run in parallel to normal processing.
  650. *
  651. * - Since the udp socket may be connectionless, its possible for unsolicited packets to arrive.
  652. * Such packets need to be ignored.
  653. *
  654. * 3. Sometimes traffic shapers are needed to simulate real world environments.
  655. * A filter allows you to write custom code to simulate such environments.
  656. * The ability to code this yourself is especially helpful when your simulated environment
  657. * is more complicated than simple traffic shaping (e.g. simulating a cone port restricted router),
  658. * or the system tools to handle this aren't available (e.g. on a mobile device).
  659. *
  660. * Example:
  661. *
  662. * GCDAsyncUdpSocketReceiveFilterBlock filter = ^BOOL (NSData *data, NSData *address, id *context) {
  663. *
  664. * MyProtocolMessage *msg = [MyProtocol parseMessage:data];
  665. *
  666. * *context = response;
  667. * return (response != nil);
  668. * };
  669. * [udpSocket setReceiveFilter:filter withQueue:myParsingQueue];
  670. *
  671. * For more information about GCDAsyncUdpSocketReceiveFilterBlock, see the documentation for its typedef.
  672. * To remove a previously set filter, invoke this method and pass a nil filterBlock and NULL filterQueue.
  673. *
  674. * Note: This method invokes setReceiveFilter:withQueue:isAsynchronous: (documented below),
  675. * passing YES for the isAsynchronous parameter.
  676. **/
  677. - (void)setReceiveFilter:(GCDAsyncUdpSocketReceiveFilterBlock)filterBlock withQueue:(dispatch_queue_t)filterQueue;
  678. /**
  679. * The receive filter can be run via dispatch_async or dispatch_sync.
  680. * Most typical situations call for asynchronous operation.
  681. *
  682. * However, there are a few situations in which synchronous operation is preferred.
  683. * Such is the case when the filter is extremely minimal and fast.
  684. * This is because dispatch_sync is faster than dispatch_async.
  685. *
  686. * If you choose synchronous operation, be aware of possible deadlock conditions.
  687. * Since the socket queue is executing your block via dispatch_sync,
  688. * then you cannot perform any tasks which may invoke dispatch_sync on the socket queue.
  689. * For example, you can't query properties on the socket.
  690. **/
  691. - (void)setReceiveFilter:(GCDAsyncUdpSocketReceiveFilterBlock)filterBlock
  692. withQueue:(dispatch_queue_t)filterQueue
  693. isAsynchronous:(BOOL)isAsynchronous;
  694. #pragma mark Closing
  695. /**
  696. * Immediately closes the underlying socket.
  697. * Any pending send operations are discarded.
  698. *
  699. * The GCDAsyncUdpSocket instance may optionally be used again.
  700. * (it will setup/configure/use another unnderlying BSD socket).
  701. **/
  702. - (void)close;
  703. /**
  704. * Closes the underlying socket after all pending send operations have been sent.
  705. *
  706. * The GCDAsyncUdpSocket instance may optionally be used again.
  707. * (it will setup/configure/use another unnderlying BSD socket).
  708. **/
  709. - (void)closeAfterSending;
  710. #pragma mark Advanced
  711. /**
  712. * GCDAsyncSocket maintains thread safety by using an internal serial dispatch_queue.
  713. * In most cases, the instance creates this queue itself.
  714. * However, to allow for maximum flexibility, the internal queue may be passed in the init method.
  715. * This allows for some advanced options such as controlling socket priority via target queues.
  716. * However, when one begins to use target queues like this, they open the door to some specific deadlock issues.
  717. *
  718. * For example, imagine there are 2 queues:
  719. * dispatch_queue_t socketQueue;
  720. * dispatch_queue_t socketTargetQueue;
  721. *
  722. * If you do this (pseudo-code):
  723. * socketQueue.targetQueue = socketTargetQueue;
  724. *
  725. * Then all socketQueue operations will actually get run on the given socketTargetQueue.
  726. * This is fine and works great in most situations.
  727. * But if you run code directly from within the socketTargetQueue that accesses the socket,
  728. * you could potentially get deadlock. Imagine the following code:
  729. *
  730. * - (BOOL)socketHasSomething
  731. * {
  732. * __block BOOL result = NO;
  733. * dispatch_block_t block = ^{
  734. * result = [self someInternalMethodToBeRunOnlyOnSocketQueue];
  735. * }
  736. * if (is_executing_on_queue(socketQueue))
  737. * block();
  738. * else
  739. * dispatch_sync(socketQueue, block);
  740. *
  741. * return result;
  742. * }
  743. *
  744. * What happens if you call this method from the socketTargetQueue? The result is deadlock.
  745. * This is because the GCD API offers no mechanism to discover a queue's targetQueue.
  746. * Thus we have no idea if our socketQueue is configured with a targetQueue.
  747. * If we had this information, we could easily avoid deadlock.
  748. * But, since these API's are missing or unfeasible, you'll have to explicitly set it.
  749. *
  750. * IF you pass a socketQueue via the init method,
  751. * AND you've configured the passed socketQueue with a targetQueue,
  752. * THEN you should pass the end queue in the target hierarchy.
  753. *
  754. * For example, consider the following queue hierarchy:
  755. * socketQueue -> ipQueue -> moduleQueue
  756. *
  757. * This example demonstrates priority shaping within some server.
  758. * All incoming client connections from the same IP address are executed on the same target queue.
  759. * And all connections for a particular module are executed on the same target queue.
  760. * Thus, the priority of all networking for the entire module can be changed on the fly.
  761. * Additionally, networking traffic from a single IP cannot monopolize the module.
  762. *
  763. * Here's how you would accomplish something like that:
  764. * - (dispatch_queue_t)newSocketQueueForConnectionFromAddress:(NSData *)address onSocket:(GCDAsyncSocket *)sock
  765. * {
  766. * dispatch_queue_t socketQueue = dispatch_queue_create("", NULL);
  767. * dispatch_queue_t ipQueue = [self ipQueueForAddress:address];
  768. *
  769. * dispatch_set_target_queue(socketQueue, ipQueue);
  770. * dispatch_set_target_queue(iqQueue, moduleQueue);
  771. *
  772. * return socketQueue;
  773. * }
  774. * - (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
  775. * {
  776. * [clientConnections addObject:newSocket];
  777. * [newSocket markSocketQueueTargetQueue:moduleQueue];
  778. * }
  779. *
  780. * Note: This workaround is ONLY needed if you intend to execute code directly on the ipQueue or moduleQueue.
  781. * This is often NOT the case, as such queues are used solely for execution shaping.
  782. **/
  783. - (void)markSocketQueueTargetQueue:(dispatch_queue_t)socketQueuesPreConfiguredTargetQueue;
  784. - (void)unmarkSocketQueueTargetQueue:(dispatch_queue_t)socketQueuesPreviouslyConfiguredTargetQueue;
  785. /**
  786. * It's not thread-safe to access certain variables from outside the socket's internal queue.
  787. *
  788. * For example, the socket file descriptor.
  789. * File descriptors are simply integers which reference an index in the per-process file table.
  790. * However, when one requests a new file descriptor (by opening a file or socket),
  791. * the file descriptor returned is guaranteed to be the lowest numbered unused descriptor.
  792. * So if we're not careful, the following could be possible:
  793. *
  794. * - Thread A invokes a method which returns the socket's file descriptor.
  795. * - The socket is closed via the socket's internal queue on thread B.
  796. * - Thread C opens a file, and subsequently receives the file descriptor that was previously the socket's FD.
  797. * - Thread A is now accessing/altering the file instead of the socket.
  798. *
  799. * In addition to this, other variables are not actually objects,
  800. * and thus cannot be retained/released or even autoreleased.
  801. * An example is the sslContext, of type SSLContextRef, which is actually a malloc'd struct.
  802. *
  803. * Although there are internal variables that make it difficult to maintain thread-safety,
  804. * it is important to provide access to these variables
  805. * to ensure this class can be used in a wide array of environments.
  806. * This method helps to accomplish this by invoking the current block on the socket's internal queue.
  807. * The methods below can be invoked from within the block to access
  808. * those generally thread-unsafe internal variables in a thread-safe manner.
  809. * The given block will be invoked synchronously on the socket's internal queue.
  810. *
  811. * If you save references to any protected variables and use them outside the block, you do so at your own peril.
  812. **/
  813. - (void)performBlock:(dispatch_block_t)block;
  814. /**
  815. * These methods are only available from within the context of a performBlock: invocation.
  816. * See the documentation for the performBlock: method above.
  817. *
  818. * Provides access to the socket's file descriptor(s).
  819. * If the socket isn't connected, or explicity bound to a particular interface,
  820. * it might actually have multiple internal socket file descriptors - one for IPv4 and one for IPv6.
  821. **/
  822. - (int)socketFD;
  823. - (int)socket4FD;
  824. - (int)socket6FD;
  825. #if TARGET_OS_IPHONE
  826. /**
  827. * These methods are only available from within the context of a performBlock: invocation.
  828. * See the documentation for the performBlock: method above.
  829. *
  830. * Returns (creating if necessary) a CFReadStream/CFWriteStream for the internal socket.
  831. *
  832. * Generally GCDAsyncUdpSocket doesn't use CFStream. (It uses the faster GCD API's.)
  833. * However, if you need one for any reason,
  834. * these methods are a convenient way to get access to a safe instance of one.
  835. **/
  836. - (CFReadStreamRef)readStream;
  837. - (CFWriteStreamRef)writeStream;
  838. /**
  839. * This method is only available from within the context of a performBlock: invocation.
  840. * See the documentation for the performBlock: method above.
  841. *
  842. * Configures the socket to allow it to operate when the iOS application has been backgrounded.
  843. * In other words, this method creates a read & write stream, and invokes:
  844. *
  845. * CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  846. * CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  847. *
  848. * Returns YES if successful, NO otherwise.
  849. *
  850. * Example usage:
  851. *
  852. * [asyncUdpSocket performBlock:^{
  853. * [asyncUdpSocket enableBackgroundingOnSocket];
  854. * }];
  855. *
  856. *
  857. * NOTE : Apple doesn't currently support backgrounding UDP sockets. (Only TCP for now).
  858. **/
  859. //- (BOOL)enableBackgroundingOnSockets;
  860. #endif
  861. #pragma mark Utilities
  862. /**
  863. * Extracting host/port/family information from raw address data.
  864. **/
  865. + (NSString *)hostFromAddress:(NSData *)address;
  866. + (uint16_t)portFromAddress:(NSData *)address;
  867. + (int)familyFromAddress:(NSData *)address;
  868. + (BOOL)isIPv4Address:(NSData *)address;
  869. + (BOOL)isIPv6Address:(NSData *)address;
  870. + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr fromAddress:(NSData *)address;
  871. + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr family:(int *)afPtr fromAddress:(NSData *)address;
  872. @end
  873. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  874. #pragma mark -
  875. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  876. @protocol GCDAsyncUdpSocketDelegate
  877. @optional
  878. /**
  879. * By design, UDP is a connectionless protocol, and connecting is not needed.
  880. * However, you may optionally choose to connect to a particular host for reasons
  881. * outlined in the documentation for the various connect methods listed above.
  882. *
  883. * This method is called if one of the connect methods are invoked, and the connection is successful.
  884. **/
  885. - (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address;
  886. /**
  887. * By design, UDP is a connectionless protocol, and connecting is not needed.
  888. * However, you may optionally choose to connect to a particular host for reasons
  889. * outlined in the documentation for the various connect methods listed above.
  890. *
  891. * This method is called if one of the connect methods are invoked, and the connection fails.
  892. * This may happen, for example, if a domain name is given for the host and the domain name is unable to be resolved.
  893. **/
  894. - (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError *)error;
  895. /**
  896. * Called when the datagram with the given tag has been sent.
  897. **/
  898. - (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag;
  899. /**
  900. * Called if an error occurs while trying to send a datagram.
  901. * This could be due to a timeout, or something more serious such as the data being too large to fit in a sigle packet.
  902. **/
  903. - (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error;
  904. /**
  905. * Called when the socket has received the requested datagram.
  906. **/
  907. - (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
  908. fromAddress:(NSData *)address
  909. withFilterContext:(id)filterContext;
  910. /**
  911. * Called when the socket is closed.
  912. **/
  913. - (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error;
  914. @end