iOS 智能家居 UDP查找网关

需求
本地化:在内网的情况下,客户也可以控制设备,并且在App上显示。

需要在外网情况下登陆过App,将账号下的网关和网关下在线的设备保存在本地。

使用CocoaAsyncSocket进行开发

github下载地址CocoaAsyncSocket
可以通过CocoaPods进行导入配置也可以通过手动导入

发送UDP包查找内网环境下的网关

使用GCDAsyncUdpSocket

1>准备工作
#import "GCDAsyncUdpSocket.h"
<GCDAsyncUdpSocketDelegate>

{//    UDP广播
    NSData *udpData;//UDP包信息
    NSString *udpHost;//IP地址
    UInt16 udpPort;//端口号
}
2>创建UDP广播
#pragma mark -创建UDP广播
- (void)makeUDP{
    [_udpSocket close];
    _udpSocket = nil;
    _udpSocket.delegate = nil;
    // 创建UDP对象
    _udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *error;
  // 绑定响应端口
    if (![_udpSocket bindToPort:8200 error:&error]) {
        NSLog(@"绑定响应端口%d失败%@",8200,error);
        [_udpSocket bindToPort:8200 error:&error];
    }
  // 加入组播组
#没有搞懂  如不写会接受到两次相同的信息 其中一次收到信息的 IP地址前会有一串::ffff:
    if (![_udpSocket joinMulticastGroup:@"224.0.0.1" error:&error]) {
        NSLog(@"加入组播组失败%@",error);
        [_udpSocket joinMulticastGroup:@"224.0.0.1" error:&error];
    }
  // 开启组播设置
    if (![_udpSocket enableBroadcast:YES error:&error]) {
        NSLog(@"开启组播设置失败%@",error);
        [_udpSocket enableBroadcast:YES error:&error];
    }
//    发送广播
    [self sendUDP];
//  开始接受数据
    if (![_udpSocket beginReceiving:&error]) {
        NSLog(@"开始接受数据失败%@",error);
        [_udpSocket beginReceiving:&error];
    }
}
3>发送UDP广播
#pragma mark -发送UDP包
- (void)sendUDP{
#UDP广播包----根据公司产品发送消息、询问公司
    Byte byte[] = {};//要发送的信息(byte)
    udpData = [NSData dataWithBytes:byte length:15];
    // UDP地址,端口
    udpHost = @"255.255.255.255";
    udpPort = 8200;
  //  发送
    [_udpSocket sendData:udpData toHost:udpHost port:udpPort withTimeout:-1 tag:0];
}
4>GCDAsyncUdpSocketDelegate代理方法
#pragma mark -GCDAsyncUdpSocketDelegate 代理方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
    
    NSLog(@"UDP广播已经发送");
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
    
    NSLog(@"UDP广播发送失败%@",error);
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
    NSLog(@"UDP广播接收到的信息%@",data);
#在这里根据数据进行解析,拿到IP地址、MAC地址、端口号跟本地存储的MAC地址进行比对,如果一样就与网关进行TCP连接
}

- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error{
    
    NSLog(@"UDP广播关闭:%@",error.description);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容