8

I need to send out a UDP broadcast from an iPhone, and then listen for a UDP response with a timeout period. I have found Apple's UDPEcho example but I am not sure if it's what I need. Also found this example to send but not receive. Basically, I need to do something simple like this:

//send the broadcast
SendUDP("255.255.255.255", targetPort, myData);
//A blocking call to get the data.  Timeout value will be short, 2 seconds at most
//An asynchronous option is ok, if it's necessary.
Response = GetFirstUDPResponse(receptionPort, timeoutValue);

//process the response
if(Response == null)
  //we timed out
else
  //process response

I'm hoping for a simple solution where I don't have to reinvent the wheel. I appreciate any advice on the best strategy to implement this!

Alex
  • 9,250
  • 11
  • 70
  • 81

2 Answers2

5

You can use cocoaAsyncSocket which is easier to use than apple native classes.
It support UDP with AsyncUdpSocket class.

AsyncUdpSocket is a UDP/IP socket networking library that wraps CFSocket. It works almost exactly like the TCP version, but is designed specifically for UDP. This includes queued non-blocking send/receive operations, full delegate support, run-loop based, self-contained class, and support for IPv4 and IPv6

Jonas Schnelli
  • 9,965
  • 3
  • 48
  • 60
Benoît
  • 7,395
  • 2
  • 25
  • 30
  • Thanks, it was easy. I provided most of my code here: http://stackoverflow.com/questions/5790149/little-problem-with-asyncudpsocket-receiving-data-after-connecting-to-broadcast-i/7682688#7682688 – Alex Oct 07 '11 at 03:34
5

I'd put 'recvfrom' on another thread using grand central dispatch, like this:

// Use grand central dispatch so we don't block the interface
dispatch_async(dispatch_get_global_queue(0, 0), ^{

    recvfrom(...) // Receive with a 2s timeout

    dispatch_async(dispatch_get_main_queue(), ^{ // The main thread stuff goes here

        if (received ok) {
            [self receivedData:some data];
        } else {
            [self timedOut];
        }

    });
});
Chris
  • 39,719
  • 45
  • 189
  • 235
  • 1
    One thing though, you may want to make sure you're listening (ie recvfrom) before you send the broadcast packet, otherwise a response may come back in the small time gap between sending and listening. However, to do this, you must bind your ephemeral port first. – Chris Oct 04 '11 at 03:32
  • i'm curious about your receive with a 2s timeout part. how do you implement this? – chancyWu Jan 09 '14 at 08:59