我正在尝试使用Boxee Remote Control Interface发送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;
}
最佳答案
我认为您的问题是您的代码仅准备接收单个数据包。您正在发送广播数据包,因此本地网络上的所有设备(包括您自己的设备)都将收到该数据包。另外,尽管我知道这只是测试代码,但网络上可能有多个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
}