iPhone UDP广播和响应

我需要从iPhone发送一个UDP广播,然后侦听超时时间的UDP响应。 我发现苹果的UDPEcho例子,但我不知道,如果这是我所需要的。 还发现这个例子发送,但没有收到。 基本上,我需要做这样简单的事情:

//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 

我希望有一个简单的解决scheme,我不必重新发明车轮。 我很欣赏任何关于实施这个最佳策略的build议!

你可以使用比苹果原生类更容易使用的cocoaAsyncSocket 。
它使用AsyncUdpSocket类来支持UDP。

AsyncUdpSocket是包装CFSocket的UDP / IP套接字networking库。 它几乎完全像TCP版本一样工作,但是专门为UDPdevise的。 这包括排队的非阻塞发送/接收操作,完全委托支持,基于运行循环的自包含类以及对IPv4和IPv6的支持

我把“recvfrom”放在另一个使用macros中央调度的线程上,像这样:

 // 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]; } }); });