iOS- 移動端Socket UDP協議廣播機制的實現


1.前言  

    什么是UDP協議廣播機制?
 
   舉一個例, 例如在一群人群中,一個人要找張三,於是你向人群里大喊一聲(廣播):“誰是張三”
  如果它是張三,它就會回應你,在網絡中也是一樣的。
 
 
    UDP廣播機制的應用場景:
 
    若干個客戶端,在局域網內(不知道IP的情況下) 需要在很多設備里需找特有的設備,比如服務器,抑或是某個打印機,傳真機等。
    
    假設我現在准備將服務器裝在永不斷電的iPad上。
    若干個客戶端iPhone 一激活,就要來向所有設備廣播,誰是服務器,是服務器的話,請把IP地址告訴我。然后我就去連接,然后進入長連接,后台接受消息。

 

2.UDP廣播機制的實現  

注:
 iPad:服務器端  iPhone:客戶端
 

2.1.服務器端(iPad)的實現  


2.1.1.先去github上下載 AsyncUdpSocket.h框架包  

www.github.com

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]; 

 

作者: 清澈Saup
出處: http://www.cnblogs.com/qingche/
本文版權歸作者和博客園共有,歡迎轉載,但必須保留此段聲明,且在文章頁面明顯位置給出原文連接。

 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM