Database Reference
In-Depth Information
Broadcasting the Service
Distributed objects work by using good old Unix sockets. Fortunately, these
are wrapped with NSSocketPort for us, so we do not need to use the raw C
functions and all the complexity that entails. To use sockets, we need to know
the address and port of the socket to talk to. This can be entered by the user,
which is a suboptimal experience, or we can discover it using Bonjour. To
use Bonjour, we must set up a broadcast on the server for the client to
discover.
DistributedCDServer/AppDelegate.m
- ( void )startBroadcasting
{
receiveSocket = [[NSSocketPort alloc] init];
int receivePort = [self portFromSocket:receiveSocket];
myConnection = [[NSConnection alloc] initWithReceivePort:receiveSocket
sendPort:nil];
[myConnection setRootObject:self];
myService = [[NSNetService alloc] initWithDomain:kDomainName
type:kServiceName
name:kServerName
port:receivePort];
[myService setDelegate:self];
[myService publish];
}
In the -startBroadcasting method, we first initialize a new NSSocketPort . When we
use the default -init method, the NSSocketPort chooses a random open port for
us to use. However, we need to broadcast this port information as part of the
Bonjour service. Therefore, we need to extract the port information from the
NSSocketPort object. In a production environment, we probably want to define
a port to use instead of selecting one at random.
DistributedCDServer/AppDelegate.m
- ( int )portFromSocket:(NSSocketPort*)socket
{
struct sockaddr *address = ( struct sockaddr*)[[receiveSocket address] bytes];
uint16_t port;
if (address->sa_family == AF_INET) {
port = ntohs((( struct sockaddr_in*)address)->sin_port);
} else if (address->sa_family == AF_INET6) {
port = ntohs((( struct sockaddr_in6*)address)->sin6_port);
} else {
@throw [NSException exceptionWithName:@ "Socket Error"
reason:@ "Unknown network type"
userInfo:nil];
}
return port;
}
 
 
 
Search WWH ::




Custom Search