服務器端Bonjour服務發布成功之後,客戶端可以通過NSNetService解析服務,解析成功後,可以獲得通訊的數據細節,如:IP地址、端口等信息。
首先需要實例化NSNetService對象代碼如下:
[cpp]
-(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;
}
-(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]語句,開始解析服務,在規定的時間裡進行解析,參數是單位是秒。
[cpp]
#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);
}
#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:方法。