The code to vend the object to the network is quite simple: you get the defaultConnection object:
NSConnection *conn = [NSConnection defaultConnection];then you tell the connection which object you want to vend:
[conn setRootObject: reader];and finally, you register it on the network with a certain name:
if (![conn registerName:@"FileReader"])
{
NSLog (@"Could not register us as FileReader");
exit (1);
}
the name is quite important - the client needs to know the name of
the server to establish a connection with it and access the vended
object (which is the FileReader object in this case).
So, here is the full code for the server:
#include <Foundation/Foundation.h>
/* This object does the job of fetching a file from
the hard disk */
@interface FileReader : NSObject
- (NSString *)getFile: (NSString *)fileName;
@end
@implementation FileReader
- (NSString *)getFile: (NSString *)fileName
{
return [NSString stringWithContentsOfFile: fileName];
}
@end
int
main (void)
{
NSAutoreleasePool *pool;
FileReader *reader;
NSConnection *conn;
pool = [NSAutoreleasePool new];
/* Create our FileReader object */
reader = [FileReader new];
/* Get the default connection */
conn = [NSConnection defaultConnection];
/* Make the reader available to other processes */
[conn setRootObject: reader];
/* Register it with name `FileReader' */
if (![conn registerName:@"FileReader"])
{
NSLog (@"Could not register us as FileReader");
exit (1);
}
NSLog (@"Server registered - waiting for connections...");
/* Now enter the run loop waiting forever for clients */
[[NSRunLoop currentRunLoop] run];
return 0;
}