iOS设备未使用GDAsyncUdpSocket接收UDP多播

下面的代码用于在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

最佳答案 你错过了一个让我困扰一段时间的关键功能.

[udpSocket enableBroadcast:YES error:&error];

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

点赞