1.前言
什么是UDP协议广播机制?
举一个例, 例如在一群人群中,一个人要找张三,于是你向人群里大喊一声(广播):“谁是张三”
如果它是张三,它就会回应你,在网络中也是一样的。
UDP广播机制的应用场景:
若干个客户端,在局域网内(不知道IP的情况下) 需要在很多设备里需找特有的设备,比如服务器,抑或是某个打印机,传真机等。
假设我现在准备将服务器装在永不断电的iPad上。
若干个客户端iPhone 一激活,就要来向所有设备广播,谁是服务器,是服务器的话,请把IP地址告诉我。然后我就去连接,然后进入长连接,后台接受消息。
2.UDP广播机制的实现
注:
iPad:服务器端 iPhone:客户端
2.1.服务器端(iPad)的实现
2.1.2.初始化udp
@interface QCViewController (){
AsyncUdpSocket *asyncUdpSocket;
}
asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
2.1.3.绑定端口
NSError *err = nil;
[asyncUdpSocket enableBroadcast:YES error:&err];
[asyncUdpSocket bindToPort:9527 error:&err];
//启动接收线程
[asyncUdpSocket receiveWithTimeout:-1 tag:0];
2.1.4.实现代理方法
//已接收到消息
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
if(data是找服务器的){
//根据客户端给的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.客户端(iPhone)的实现
注:实现步骤与服务器端相似
2.2.1.初始化udp
@interface QCViewController (){
AsyncUdpSocket *asyncUdpSocket;
}
asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
2.2.2.绑定端口
NSError *err = nil;
[asyncUdpSocket enableBroadcast:YES error:&err];
[asyncUdpSocket bindToPort:9527 error:&err];
2.2.3.实现代理方法
//已接收到消息
- (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.4.广播寻找
注:广播iP地址为 255.255.255.255
NSString *str = @"谁是服务器?我的IP是:192.168.80.103";
NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
[asyncUdpSocket sendData:data
toHost:@"255.255.255.255
port:9527
withTimeout:-1
tag:0];