服务器端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:方法。