没有使用GDAsyncUdpSocket接收UDP多播的iOS设备

下面的代码旨在接收239.255.255.250上的UDP多播消息,并简单地NSLog消息的内容。

如果我将消息发送到iOS设备的IP地址(即从terminalecho foo | nc -u 10.1.10.249 1900 ),则会收到消息并进行NSLog。

但是,如果我将消息广播到多播地址( echo bar | nc -u 239.255.255.250 1900 ),则不会收到该消息。

启动时不logging错误消息。

关于我要去哪里的错误?

 #import "ViewController.h" #import "GCDAsyncUdpSocket.h" @interface ViewController () { GCDAsyncUdpSocket *udpSocket; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; NSError *error = nil; if (![udpSocket bindToPort:1900 error:&error]) { NSLog(@"Error starting server (bind): %@", error.description ); return; } if(![udpSocket joinMulticastGroup:@"239.255.255.250" error:&error] ) { //]onInterface:@"en0" error:&error]) { NSLog(@"Error joining multicast group: %@",error.description); return; } if (![udpSocket beginReceiving:&error]) { [udpSocket close]; NSLog(@"Error starting server (recv): %@", error.description); return; } NSLog(@"Udp server started on port %@:%hu", [udpSocket localHost_IPv4], [udpSocket localPort]); } - (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext { NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"message rec'd: %@:%hu %@\n", [udpSocket localHost_IPv4], [udpSocket localPort],msg); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end 

你错过了一段时间也困扰我的关键function。

 [udpSocket enableBroadcast:YES error:&error]; 

这将允许您发送广播数据包并从您的多播组接收广播数据包。