我正在构建一个发送多播消息 (SSDP) 并侦听来自实现该协议的设备的响应的 iOS 应用程序。我正在使用 GCDAsyncUdpSocket 创建 UDP 套接字来广播 SSDP 消息并接收响应。我遇到的问题是应用程序从网络上的所有设备接收到的消息是相同的:HTTP 412
响应。
这是我的代码:
初始化套接字
@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:0 error:&error])
{
NSLog(@"Error binding: %@", [error description]);
return;
}
if (![udpSocket beginReceiving:&error])
{
NSLog(@"Error receiving: %@", [error description]);
return;
}
[udpSocket enableBroadcast:YES error:&error];
if (error != nil)
{
NSLog(@"Error enableing broadcast: %@", [error description]);
return;
}
NSLog(@"Socket Created");
}
创建套接字
- (IBAction)socketFind:(id)sender
{
NSString *str = [[NSString alloc] initWithString:@"M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp discover\"\r\nMX: 3\r\nST: ssdp:all\r\nUSER-AGENT: iOS UPnP/1.1 TestApp/1.0\r\n\r\n"];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:@"239.255.255.250" port:1900 withTimeout:-1 tag:0];
NSLog(@"Sent Data");
}
数据接收回调
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSLog(@"Did Receive Data");
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
NSLog(@"Message: %@",msg);
}
else
{
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
NSLog(@"Unknown Message: %@:%hu", host, port);
}
}
调用该didReceiveData
函数时,我收到以下消息:
Message: HTTP/1.1 412 Precondition Failed
Connection:close
CONTENT-LENGTH:0