1

我正在尝试使用Boxee 远程控制接口发送 UDP 广播以发现设备。

目前正在使用AsyncUdpSocket,但在发送请求时,我只是将请求作为响应返回,而不是得到预期的响应。

这是我的代码,我错过了什么吗?:

- (void)viewDidLoad
{
    [super viewDidLoad];

    AsyncUdpSocket *socket  = [[AsyncUdpSocket alloc] initWithDelegate:self];
    [socket enableBroadcast:YES error:nil];
    [socket bindToPort:2562 error:nil];

    NSString *xml           = @"<?xml version=\"1.0\"?><BDP1 cmd=\"discover\" application=\"iphone_remote\" challenge=\"shittycitttyy123\" signature=\"cdddac43fdbce83d24b7c1ca5149c697\"/>";


    NSData *data            = [xml dataUsingEncoding:NSUTF8StringEncoding];

    if([socket sendData:data toHost:@"10.0.0.255" port:2562 withTimeout:3 tag:0]){
        [socket receiveWithTimeout:2 tag:0];
    }
}

-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
    NSLog(@"Got data %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

    return YES;
}
4

1 回答 1

2

我认为你的问题是你的代码只准备接收一个数据包。您正在发送一个广播数据包,因此本地网络上的所有设备都将收到该数据包 - 包括您自己的设备,这就是您所看到的。此外,虽然我知道这只是测试代码,但网络上可能有多个 Boxee 盒子,因此您可以预期多个回复的可能性。

尝试这样的事情 -

 (void)viewDidLoad
{
    [super viewDidLoad];

    AsyncUdpSocket *socket  = [[AsyncUdpSocket alloc] initWithDelegate:self];
    [socket enableBroadcast:YES error:nil];
    [socket bindToPort:2562 error:nil];

    NSString *xml           = @"<?xml version=\"1.0\"?><BDP1 cmd=\"discover\" application=\"iphone_remote\" challenge=\"shittycitttyy123\" signature=\"cdddac43fdbce83d24b7c1ca5149c697\"/>";


    NSData *data            = [xml dataUsingEncoding:NSUTF8StringEncoding];

    if([socket sendData:data toHost:@"10.0.0.255" port:2562 withTimeout:3 tag:0]){
        [socket receiveWithTimeout:2 tag:0];
    }
}

-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
    NSLog(@"Got data %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

    //TODO - process incoming packet and determine if it is a Boxee response

    [socket receiveWithTimeout:2 tag:tag+1];  //Look for more data
    return YES;
}

- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error
{
   NSLog(@"Did not receive data");  
   //TODO check error and take appropriate action
}
于 2014-03-31T01:44:16.970 回答