iOS设备使用GDAsyncUdpSocket无法接收UDP组播数据包

4
以下代码旨在接收239.255.255.250上的UDP多播消息,并仅简单地将消息内容NSLog记录下来。
如果我将消息寄到iOS设备的IP地址(即从终端echo foo | nc-u 10.1.10.249 1900),则会收到消息并记录在NSLog中。
但是,如果我向多播地址广播消息(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

先生,您找到解决方案了吗? - Anoop
1个回答

2
您缺少一个关键函数,这个函数曾经让我也感到困惑了一段时间。
[udpSocket enableBroadcast:YES error:&error];

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

嘿,如果在同一WiFi情况下,这对我有效。但是如果我们启用热点,是否有任何解决方案? - Anoop
我不知道有什么办法可以在使用手机热点时使其工作,这与底层网络模型有关,该模型有意将自身与热点网络分离。 - Charles Maria

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接