1

使用 GCDAsyncudpSocket 从广播地址发送 udp 数据包和监听数据。
当我从 mac OS X Yosmite(Xcode -> device ipad air 8.2)的调试器模式运行应用程序时,它工作正常。当我在设备中安装 IPA 时它不起作用。

这是我使用的以下代码:****send****

 GCDAsyncUdpSocket * udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error = nil;

NSTimeInterval timeout= 1;
// Send the broadcast request, ie "Any upnp devices out there?"
char request[35];
request[0] = (Byte) 0xAA;
request[1] = (Byte) 0xAA;
request[sizeof(request)-2] = (Byte)0x55;
request[sizeof(request)-1] = (Byte)0x55;

NSData *data = [NSData dataWithBytes:request length:sizeof(request)];
UInt16 port=2918;
NSLog(@"begin scan");
if (![udpSocket bindToPort:port error:&error])
{
    NSLog(@"Error binding: %@", error);
    return;
}
if (![udpSocket beginReceiving:&error])
{
     NSLog(@"Error receiving: %@", error);
    return;
}
if (![udpSocket enableBroadcast:YES error:&error]) {
    NSLog(@"Error enableBroadcast: %@",error);
    return;
}
[udpSocket enableBroadcast:YES error: &error];
    [udpSocket setIPv4Enabled:YES];
    [udpSocket setIPv6Enabled:NO];
[udpSocket sendData :data toHost:[self getBroadcastAdress] port:port withTimeout:timeout tag:0];

受到 :

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
      fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString *host = nil;
    uint16_t port = 0;
    [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
    if(![host containsString:deviceIPAddress])
//    if ([host rangeOfString:deviceIPAddress].location == NSNotFound)
    {
            {
                if(![discoveredIPAddress contains Object:[[host componentsSeparatedByString:@":"] last Object]])
                    [discoveredIPAddress add Object:[[host componentsSeparatedByString:@":"] last Object]];
                N Slog(@"Printer IP: %@", discoveredIPAddress);

            }

}
}

立即帮助将不胜感激。谢谢

4

0 回答 0