Bonjour Discovery sample (Cocoa)

This sample demonstrates how to use the Bonjour service discovery mechanism for discovering services on the network. Bonjour is the facility similar to and compatible with ROZeroConf shipped with Mac OS.

Server Requirements

Thos sample requires the BonjourDiscovery sample server from Delphi samples set. Also make sure any ZeroConf facilities (Bonjour for Windows) are running on the Windows host.

Getting Started

Build and launch the BonjourDiscovery sample server, click the button on its form to activate it. Build and launch the sample. If your server is discoverable you will see the corresponding record in the services table view. It may take a couple of seconds for the client to discover the service. Once the service is discovered, select it and click the ''Use service'' button. Check the log window below to see how the client communicates with the service. Shut down the sample server and the corresponding service record should disappear from the list soon.

Examine the code

The AppController class is responsible for the sample operations. Examine the -(id)init constructor to see how the net service browser class instance is created and set up. Pay special attention to how the target service type the browser will look for is represented.

netServiceBrowser = [[NSNetServiceBrowser alloc] init];
[netServiceBrowser setDelegate:self];
[netServiceBrowser searchForServicesOfType:@"_bonjourdiscoverableservice_rosdk._tcp." inDomain:@""];

See how services availability changes are handled by two delegate methods: -(void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didFindService:(NSNetService *)netService moreComing:(BOOL)moreServicesComing:

[services addObject:netService];
[services setSelectionIndex:([[services arrangedObjects] count] - 1)];
[netService setDelegate:self];
[netService resolveWithTimeout:1];

and -(void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didRemoveService:(NSNetService *)netService moreComing:(BOOL)moreServicesComing. Also notice that full service discovery is a two-stage process and the delegate method -(void)netServiceDidResolveAddress:(NSNetService *)sender will be called when the discovered service details become known:

-(void)netServiceDidResolveAddress:(NSNetService *)sender
{
    [self addToLog:[NSString stringWithFormat:@"Service resolved. Host name: %@ Port number: %@", 
                    [sender hostName], [NSNumber numberWithInt:[sender port]]]];
    [services rearrangeObjects];
}