How to receive Multicast UDP?

一笑奈何 提交于 2020-01-01 18:44:08

问题


I'm using GCDAsyncUdpSocket and i can send either Multicast or normal UDP packets. I'm receiving normal packets with no problem but I cant receive Multicast packets from another iOS device.

To receive I use:

- (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:


Make sure the socket is properly set up for multicast. Here's what I'm doing in my multicast project:

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


来源:https://stackoverflow.com/questions/13459116/how-to-receive-multicast-udp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!