home *** CD-ROM | disk | FTP | other *** search
/ NeXTSTEP 3.0 / NeXTSTEP3.0.iso / NextDeveloper / Examples / DistributedObjects / MultipleThreads / MultiThreadedServer.m
Text File  |  1992-07-24  |  2KB  |  73 lines

  1. #import <objc/Object.h>
  2. #import <remote/NXCo@btion.h>
  3. #import <remote/NXProxy.h>
  4. #import <mach/cthreads.h>
  5. #import <machkit/NXPort.h>
  6.  
  7. /*
  8.  * A simple, multi-threaded example.
  9.  * Each new client gets a dedicated thread.
  10.  */
  11.  
  12. @protocol ServerProtocol
  13. - newThread;
  14. - (int) doWork;
  15. @end
  16.  
  17. @interface MTS : Object <ServerProtocol>
  18. @end
  19.  
  20. @implementation MTS
  21. // when a new client shows up, build a private connection to it
  22. - connection: (NXConnection *)oldConn didConnect:(NXConnection *)newConn {
  23.     id    outPort = [newConn outPort];
  24.     NXProxy *bogus = [NXConnection connectToPort:outPort];
  25.     NXConnection *newnewConn = [bogus connectionForProxy];
  26.  
  27.     [newConn free];    // don't need new connection on old inPort
  28.     [newnewConn runInNewThread];    // service new things in new thread
  29.     [newnewConn setRoot:self];    // give new conn a root to serve!
  30.     return newnewConn;    // service this first request in main thread
  31. }
  32. - newThread {
  33.     return self;    // this will point to newnewConn (and new thread)
  34. }
  35. - (int) doWork {
  36.     return (int) cthread_self();
  37. }
  38. @end
  39.  
  40. main() {
  41.     MTS *mts;
  42.     NXConnection *server;
  43.     id proxy1, proxy2;
  44.  
  45. //    [NXConnection debug:"MTS "];
  46.     mts = [MTS new];
  47.     server = [NXConnection registerRoot:mts withName:"MTS example"];
  48.     if (server) {    // we're it!
  49.         [server setDelegate:mts];
  50.         [server run];
  51.     }
  52.     else {
  53.         [mts free];
  54.         proxy1 = [NXConnection connectToName:"MTS example"];
  55.  
  56.         if (!proxy1) {
  57.             printf("couldn't get to server\n");
  58.             exit(1);
  59.         }
  60.         [proxy1 setProtocolForProxy:@protocol(ServerProtocol)];
  61.  
  62.         proxy2 = [proxy1 newThread];
  63.         if (!proxy2) {
  64.             printf("couldn't get new thread\n");
  65.             exit(2);
  66.         }
  67.         [proxy2 setProtocolForProxy:@protocol(ServerProtocol)];
  68.  
  69.         printf("new thread is %x\n", [proxy2 doWork]);
  70.     }
  71.     exit(0);
  72. }
  73.