PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/External/Quickblox.framework/Versions/A/Headers/Core/External/TURN/Vendors/QBGCDAsyncUdpSocket.h

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