iOS 利用Socket UDP協議廣播機制的實現
1.前言
什麼是UDP協議廣播機制?
舉一個例, 例如在一群人群中,一個人要找張三,於是你向人群裡大喊一聲(廣播):“誰是張三”
如果它是張三,它就會回應你,在網路中也是一樣的。
UDP廣播機制的應用情境:
若干個用戶端,在區域網路內(不知道IP的情況下) 需要在很多裝置裡需找特有的裝置,比如伺服器,抑或是某個印表機,傳真機等。
假設我現在準備將伺服器裝在永不斷電的iPad上。
若干個用戶端iPhone 一啟用,就要來向所有裝置廣播,誰是伺服器,是伺服器的話,請把IP地址告訴我。然後我就去串連,然後進入長串連,後台接受訊息。
2.UDP廣播機制的實現
註:iPad:伺服器端 iPhone:用戶端
2.1.伺服器端(iPad)的實現
//初始化udp
AsyncUdpSocket *asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
//綁定連接埠
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是找伺服器的){
//根據用戶端給的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)的實現
註:實現步驟與伺服器端相似
//初始化udp
AsyncUdpSocket *asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
//綁定連接埠
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 = @誰是伺服器?我的IP是:192.168.80.103;
NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
[asyncUdpSocket sendData:data toHost:@255.255.255.255 port:9527 withTimeout:-1 tag:0];