如何接收多播UDP?(How to receive Multicast UDP?)

2019-08-02 23:01发布

我使用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");
}
}

Answer 1:

确保插座已正确设置了多播。 这是我在我的组播项目正在做的:

- (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");
}


文章来源: How to receive Multicast UDP?