Database Reference
In-Depth Information
-netServiceBrowser:didFindService: Implementation
Every time the
NSNetServiceBrowser
finds a service, it calls this method. If it finds
more than one server in a single sweep of the network, it calls this method
once per service, and the
moreComing:
will be set to
YES
.
- (
void
)netServiceBrowser:(NSNetServiceBrowser*)browser
didFindService:(NSNetService*)service
moreComing:(BOOL)more
{
[service retain];
[service setDelegate:self];
[service resolveWithTimeout:5.0];
[service startMonitoring];
[browser stop];
[browser release], browser = nil;
}
In our implementation, we want to connect to a server as soon as we find
one. We are not worried about multiple servers on the network, so the first
that comes in will do. Once we receive notice that a service matching our
search criteria is available, we start monitoring it. This causes the
NSNetService-
Browser
to attempt to resolve the service. Once the service is resolved, the
service's delegate receives notification. Therefore, we set the
AppDelegate
as the
delegate to the service. Since we care about only a single service, we shut
down the browser and release it.
-netServiceDidResolveAddress: Implementation
Once the service has been resolved, the
NSNetService
calls
-netService-DidResolveAd-
dress:
on its delegate. When this method is called, we can retrieve the address
and port information about the service, which lets us connect to it and begin
using distributed objects.
- (
void
)netServiceDidResolveAddress:(NSNetService*)service
{
NSConnection *clientConnection = nil;
NSSocketPort *socket = nil;
NSData *address = [[service addresses] lastObject];
u_char family = ((
struct
sockaddr*)[address bytes])->sa_family;
socket = [[NSSocketPort alloc] initRemoteWithProtocolFamily:family
socketType:SOCK_STREAM
protocol:IPPROTO_TCP
address:address];
clientConnection = [NSConnection connectionWithReceivePort:nil
sendPort:socket];
server = [clientConnection rootProxy];