iOS 设备未使用 GDAsyncUdpSocket 接收 UDP 多播

iOS devices not receiving UDP multicast using GDAsyncUdpSocket(iOS 设备未使用 GDAsyncUdpSocket 接收 UDP 多播)

本文介绍了iOS 设备未使用 GDAsyncUdpSocket 接收 UDP 多播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码旨在在 239.255.255.250 上接收 UDP 多播消息,并简单地 NSLog 消息的内容.

The code below is intended to receive UDP multicast messages on 239.255.255.250 and simply NSLog the contents of the message.

如果我将消息发送到 iOS 设备的 IP(即来自终端 echo foo | nc -u 10.1.10.249 1900),则会收到消息并 NSLog'd.

If I address a message to the IP of the iOS device (i.e. from a terminal echo foo | nc -u 10.1.10.249 1900) the message is received and NSLog'd.

但是,如果我将消息广播到多播地址(echo bar | nc -u 239.255.255.250 1900),则不会收到消息.

However, if I broadcast a message to the multicast address (echo bar | nc -u 239.255.255.250 1900), the message is not received.

启动时不记录错误消息.

No error messages are logged at start up.

想好我要去哪里了吗?

#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 %@
", [udpSocket localHost_IPv4], [udpSocket localPort],msg);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end

推荐答案

你也错过了一个让我很困惑的关键功能.

You're missing a key function that stumped me for a time, too.

[udpSocket enableBroadcast:YES error:&error];

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

This will allow you to send broadcast packets and receive broadcasted packets from your multicast group.

这篇关于iOS 设备未使用 GDAsyncUdpSocket 接收 UDP 多播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:iOS 设备未使用 GDAsyncUdpSocket 接收 UDP 多播

基础教程推荐