4

下面的代码旨在在 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
4

1 回答 1

2

你错过了一个让我难过一段时间的关键功能,也是。

[udpSocket enableBroadcast:YES error:&error];

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

于 2014-07-16T05:11:05.477 回答