How can I pause reading packets from NEUDPSession

Hi There,

NWUDPSession has a setReadHandler:maxDatagrams: method to register a callback for reading packets. I am wondering how can I pause this handler not to be called for a short period(pause it for a while)?

I can think of few options, but all of them seem to be bad.
  1. Cancel the session when paused, and create a new one when resumed.

Code Block
-(void)stopReadingPackets {
[self.session cancel];
}
-(void)resume {
self.session = ...
[self.session
setReadHandler:^(NSArray<NSData*>* datagrams, NSError* error) {
// Handle packets here.
}
maxDatagrams:1];
}

2. Block the handler to be executed. For example:
Code Block
[self.session
setReadHandler:^(NSArray<NSData*>* datagrams, NSError* error) {
while (self.paused) {}
// Handle datagrams here.
}
maxDatagrams:1];




Thanks.
Yeah, that’s tricky. Do you need to use NWUDPSession here? I generally encourage folks, even folks working on Network Extension providers, to switch to using NWConnection for UDP. NWConnection has a different model for reading, one that supports flow control.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Hi Quinn,

Thanks for the response. I think we can use NWConnection over NWUDPSession as all we need is to connect to our VPN server to send/receive encrypted packets and perform handshakes.

But I am not sure how I can pause reading packets using NWConnection either, one guess would be:
Code Block
func startReadingPackets() {
connection.receiveMessage { [weak self] data, context, success, error in
/* Handle packets or error here. */
while (self?.paused) {}
self?.startReadingPackets()
}
}

Code Block
while (self?.paused) {}


Yikes! don’t do that. There’s two problems here:
  • You’re polling, which is never a good idea.

  • You’re blocking the packet receive thread, which is also a bad idea.

Rather, to exert read-side flow control you should simply not call startReadingPackets(…) in your completion handler. Then, when you want to release that flow control, call startReadingPackets(…) from the code that’s doing that release.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
How can I pause reading packets from NEUDPSession
 
 
Q