伺服器端Bonjour服務發布成功之後,用戶端可以通過NSNetService解析服務,解析成功後,可以獲得通訊的資料細節,如:IP地址、連接埠等資訊。
首先需要執行個體化NSNetService對象代碼如下:
-(id)init { _service = [[NSNetService alloc] initWithDomain:@”local.” type:@”_tonyipp._tcp.” name:@”tony”]; [_service setDelegate:self]; //設定解析地址逾時時 [_service resolveWithTimeout:1.0]; _services = [[NSMutableArray alloc] init]; return self; }
執行個體化NSNetService對象的構造方法是– initWithDomain:type:name:,不需要指定它的連接埠。解析服務需要調用 [_service resolveWithTimeout:1.0]語句,開始解析服務,在規定的時間裡進行解析,參數是單位是秒。
#pragma mark - NSNetServiceDelegate Methods - (void)netServiceWillResolve:(NSNetService *)netService { NSLog(@”netServiceWillResolve”); } - (void)netServiceDidResolveAddress:(NSNetService *)netService { NSLog(@”netServiceDidResolveAddress”); [_services addObject:netService]; } - (void)netService:(NSNetService *)netService didNotResolve:(NSDictionary *)errorDict { NSLog(@”didNotResolve: %@”,errorDict); }
netServiceWillResolve:方法在解析開始時回調,解析成功時回調netServiceDidResolveAddress:方法,解析失敗時回調netService:didNotResolve:方法。
本文出自 “關東升” 部落格,請務必保留此出處http://2009315319.blog.51cto.com/701759/1179965