需求
本地化:在內(nèi)網(wǎng)的情況下,客戶也可以控制設(shè)備,并且在App上顯示。
需要在外網(wǎng)情況下登陸過(guò)App,將賬號(hào)下的網(wǎng)關(guān)和網(wǎng)關(guān)下在線的設(shè)備保存在本地。
使用CocoaAsyncSocket進(jìn)行開發(fā)
github下載地址CocoaAsyncSocket
可以通過(guò)CocoaPods進(jìn)行導(dǎo)入配置也可以通過(guò)手動(dòng)導(dǎo)入
發(fā)送UDP包查找內(nèi)網(wǎng)環(huán)境下的網(wǎng)關(guān)
使用GCDAsyncUdpSocket
1>準(zhǔn)備工作
#import "GCDAsyncUdpSocket.h"
<GCDAsyncUdpSocketDelegate>
{// UDP廣播
NSData *udpData;//UDP包信息
NSString *udpHost;//IP地址
UInt16 udpPort;//端口號(hào)
}
2>創(chuàng)建UDP廣播
#pragma mark -創(chuàng)建UDP廣播
- (void)makeUDP{
[_udpSocket close];
_udpSocket = nil;
_udpSocket.delegate = nil;
// 創(chuàng)建UDP對(duì)象
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error;
// 綁定響應(yīng)端口
if (![_udpSocket bindToPort:8200 error:&error]) {
NSLog(@"綁定響應(yīng)端口%d失敗%@",8200,error);
[_udpSocket bindToPort:8200 error:&error];
}
// 加入組播組
#沒有搞懂 如不寫會(huì)接受到兩次相同的信息 其中一次收到信息的 IP地址前會(huì)有一串::ffff:
if (![_udpSocket joinMulticastGroup:@"224.0.0.1" error:&error]) {
NSLog(@"加入組播組失敗%@",error);
[_udpSocket joinMulticastGroup:@"224.0.0.1" error:&error];
}
// 開啟組播設(shè)置
if (![_udpSocket enableBroadcast:YES error:&error]) {
NSLog(@"開啟組播設(shè)置失敗%@",error);
[_udpSocket enableBroadcast:YES error:&error];
}
// 發(fā)送廣播
[self sendUDP];
// 開始接受數(shù)據(jù)
if (![_udpSocket beginReceiving:&error]) {
NSLog(@"開始接受數(shù)據(jù)失敗%@",error);
[_udpSocket beginReceiving:&error];
}
}
3>發(fā)送UDP廣播
#pragma mark -發(fā)送UDP包
- (void)sendUDP{
#UDP廣播包----根據(jù)公司產(chǎn)品發(fā)送消息、詢問公司
Byte byte[] = {};//要發(fā)送的信息(byte)
udpData = [NSData dataWithBytes:byte length:15];
// UDP地址,端口
udpHost = @"255.255.255.255";
udpPort = 8200;
// 發(fā)送
[_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廣播已經(jīng)發(fā)送");
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
NSLog(@"UDP廣播發(fā)送失敗%@",error);
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
NSLog(@"UDP廣播接收到的信息%@",data);
#在這里根據(jù)數(shù)據(jù)進(jìn)行解析,拿到IP地址、MAC地址、端口號(hào)跟本地存儲(chǔ)的MAC地址進(jìn)行比對(duì),如果一樣就與網(wǎng)關(guān)進(jìn)行TCP連接
}
- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error{
NSLog(@"UDP廣播關(guān)閉:%@",error.description);
}