Next: 5 The client Up: GNUstep Distributed Objects Previous: 3 Extending the program

4 The server

We put the source code for the server in the Server.m file. Basically, the server consists of the FileReader class, plus a new main function, which creates an instance of FileReader and vends it to the network, that is, it exposes it to the network, allowing other remote processes to call its methods via GNUstep Distributed Objects. Then, the server enters into a run-loop waiting for something to happen.

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;
}



2011-02-09