1.前言
什么是UDP协议广播机制?
举一个例。 比如在一群人群中,一个人要找张三,于是你向人群里大喊一声(广播):“谁是张三”
假设它是张三,它就会回应你。在网络中也是一样的。
UDP广播机制的应用场景:
若干个client。在局域网内(不知道IP的情况下) 须要在非常多设备里需找特有的设备,比方server,抑或是某个打印机,传真机等。
如果我如今准备将server装在永不断电的iPad上。
若干个clientiPhone 一激活。就要来向全部设备广播,谁是server。是server的话,请把IP地址告诉我。
然后我就去连接。然后进入长连接,后台接受消息。
2.UDP广播机制的实现
注:iPad:server端 iPhone:client
2.1.server端(iPad)的实现
//初始化udp
AsyncUdpSocket *asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
//绑定port
NSError *err = nil;
[asyncUdpSocket enableBroadcast:YES error:&err];
[asyncUdpSocket bindToPort:9527 error:&err];
//启动接收线程
[asyncUdpSocket receiveWithTimeout:-1 tag:0];
2.1.1.实现代理方法
//已接收到消息
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
if(data是找server的){
//依据client给的IP,利用TCP或UDP 相互连接上就能够開始通讯了
} return YES;
}
//没有接受到消息
-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{
}
//没有发送出消息
-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
}
//已发送出消息
-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
}
//断开连接
-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{
}
2.2.client(iPhone)的实现
注:实现步骤与server端相似
//初始化udpAsyncUdpSocket *asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
//绑定port
NSError *err = nil;
[asyncUdpSocket enableBroadcast:YES error:&err];
[asyncUdpSocket bindToPort:9527 error:&err];
2.2.1.实现代理方法
//已接收到消息
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
return YES;
}
//没有接受到消息
-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{
}
//没有发送出消息
-(void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
}
//已发送出消息
-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
}
//断开连接
-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock{
}
2.2.2.广播寻找
注:广播iP地址为 255.255.255.255
NSString *str = @"谁是server?我的IP是:192.168.80.103";
NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
[asyncUdpSocket sendData:data toHost:@"255.255.255.255" port:9527 withTimeout:-1 tag:0];