以下代码用于在239.255.255.250上接收UDP多播消息,并且只是NSLog消息的内容。
如果我将消息发送到iOS设备的IP(即从终端echo foo | nc -u 10.1.10.249 1900
),则会收到消息并且NSLog' d。
但是,如果我向多播地址(echo bar | nc -u 239.255.255.250 1900
)广播消息,则不会收到消息。
启动时不会记录任何错误消息。
关于我出错的地方的想法?
#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
答案 0 :(得分:2)
你错过了一段关键的功能,也让我感到难过。
[udpSocket enableBroadcast:YES error:&error];
这将允许您发送广播数据包并从您的多播组接收广播数据包。