2

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

1 回答 1

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");
}
于 2013-01-03T03:01:08.877 回答