如何接收多播UDP?

时间:2012-11-19 17:35:20

标签: objective-c multicast asyncsocket

我正在使用GCDAsyncUdpSocket,我可以发送多播或普通UDP数据包。我收到正常的数据包没有问题,但我无法接收来自其他iOS设备的多播数据包。

接收我使用:

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:   (NSData *)address withFilterContext:(id)filterContext
{ NSString *msg = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];

NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];

if (msg)
{   
    NSLog(@"Message = %@, Adress = %@ %i",msg,host,port);
}
else
{
    NSLog(@"Error converting received data into UTF-8 String");
}
}

1 个答案:

答案 0 :(得分:7)

确保套接字已正确设置为多播。这是我在多播项目中所做的事情:

- (void)setupSocket
{
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error = nil;
    if (![udpSocket bindToPort:5555 error:&error])
    {
        NSLog(@"Error binding to port: %@", error);
        return;
    }
    if(![udpSocket joinMulticastGroup:@"226.1.1.1" error:&error]){
        NSLog(@"Error connecting to multicast group: %@", error);
        return;
    }
    if (![udpSocket beginReceiving:&error])
    {
        NSLog(@"Error receiving: %@", error);
        return;
    }
    NSLog(@"Socket Ready");
}