/usr/share/GNUstep/Documentation/Developer/Base/ProgrammingManual/gs-base/Distributed-Objects.html is in gnustep-base-doc 1.25.1-2ubuntu3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by GNU Texinfo 6.5, http://www.gnu.org/software/texinfo/ -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Distributed Objects (Objective-C GNUstep Base Programming Manual)</title>
<meta name="description" content="Distributed Objects (Objective-C GNUstep Base Programming Manual)">
<meta name="keywords" content="Distributed Objects (Objective-C GNUstep Base Programming Manual)">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<link href="index.html#Top" rel="start" title="Top">
<link href="Make.html#Make" rel="index" title="Make">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="index.html#Top" rel="up" title="Top">
<link href="Base-Library.html#Base-Library" rel="next" title="Base Library">
<link href="Exception-Handling.html#Exception-Handling" rel="prev" title="Exception Handling">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.indentedblock {margin-right: 0em}
blockquote.smallindentedblock {margin-right: 0em; font-size: smaller}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
kbd {font-style: oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nolinebreak {white-space: nowrap}
span.roman {font-family: initial; font-weight: normal}
span.sansserif {font-family: sans-serif; font-weight: normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en">
<a name="Distributed-Objects"></a>
<div class="header">
<p>
Next: <a href="Base-Library.html#Base-Library" accesskey="n" rel="next">Base Library</a>, Previous: <a href="Exception-Handling.html#Exception-Handling" accesskey="p" rel="prev">Exception Handling</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Make.html#Make" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Distributed-Objects-1"></a>
<h2 class="chapter">7 Distributed Objects</h2>
<a name="index-distributed-objects"></a>
<p>Until now we have been concentrating on using the Objective-C language
to create programs that execute in a single process. But what if you
want your program to interact with objects in other processes, perhaps
running on different machines?
</p>
<p>As a simple example, we may have a client process that needs to access a
telephone directory stored on a remote server. The client process could
send a message to the server that contained a person’s name, and the
server could respond by returning that person’s number.
</p>
<p>The GNUstep base library provides a powerful set of classes that make
this type of remote messaging not only possible, but easy to program. So
what do these classes do and how can we use them? To answer that we must
first look at the way code interacts with objects in a single process,
and then look at how we can achieve the same interaction with objects
that exist in different processes.
</p>
<a name="Object-Interaction"></a>
<h3 class="section">7.1 Object Interaction</h3>
<a name="index-object-interaction_002c-remote-objects"></a>
<p>To continue with the example above, if the telephone directory existed
in the same process as the code that was accessing it, then a simple
message would return the wanted telephone number.
</p>
<div class="example">
<pre class="example"> NSString *wantedNumber = [telephoneDirectory teleNumber: personName];
</pre></div>
<p>Now object and method names just hold pointers to memory addresses. The
code executed at run time in response to the <code>teleNumber</code> message
is located at an address held by the name of the responding method (a
variable), while data in the telephone directory is located at an
address held by the <code>telephoneDirectory</code> variable.
</p>
<p>In a single process these addresses can be accessed by the client code
at run time, but if the telephone directory is located on a remote
server, then the address of the remote object is not known in the client
process (the <code>telephoneDirectory</code> object and its responding method
are said to exist in a separate ’address space’).
</p>
<p>The Objective-C run-time library was not designed for this inter-process
communication or ’remote messaging’.
</p>
<a name="The-GNUstep-Solution"></a>
<h3 class="section">7.2 The GNUstep Solution</h3>
<a name="index-distributed-objects-1"></a>
<a name="index-remote-objects"></a>
<a name="index-client_002fserver-processes"></a>
<a name="index-NSConnection-class"></a>
<a name="index-NSProxy-class"></a>
<a name="index-NSRunLoop-class"></a>
<p>GNUstep overcomes these limitations by providing you with classes that
form what is known as a ’distributed objects’ architecture that
extends the capabilities of the run-time system.
</p>
<p>With the addition of a few lines of code in the client and server
programs, these extensions allow you to send a message to a remote
process by constructing a simple Objective-C statement. In the telephone
directory example, the statement to retrieve the telephone number would
now look something like this:
</p>
<div class="example">
<pre class="example"> NSString *wantedNumber = [proxyForDirectory teleNumber: personName];
</pre></div>
<p>Compare this to the original statement:
</p>
<div class="example">
<pre class="example"> NSString *wantedNumber = [telephoneDirectory teleNumber: personName];
</pre></div>
<p>Notice that the only difference between the two statements is the name
of the object receiving the message, i.e. <code>proxyForDirectory</code>
rather than <code>telephoneDirectory</code>. GNUstep makes it as simple as
this to communicate with an object in another process.
</p>
<p>The variable <code>proxyForDirectory</code> is known as a ’proxy’ for the
remote <code>telephoneDirectory</code> object. A proxy is simply a substitute
for the remote object, with an address in the ’address space’ of the
local client process, that receives messages and forwards them on to the
remote server process in a suitably coded form.
</p>
<p>Let us now take a look at the additional lines of code required to make
this ’remote messaging’ possible.
</p>
<a name="Code-at-the-Server"></a>
<h4 class="subsection">7.2.1 Code at the Server</h4>
<a name="index-distributed-objects_002c-client-code"></a>
<p>In order to respond to client messages, the responding server object must be
set as the ’root object’ of an instance of the <code>NSConnection</code> class, and
this <code>NSConnection</code> must be registered with the network by name. Making
an object available to client processes in this way is known as ’vending’ the
object. The registered name for the <code>NSConnection</code> is used by the client
when obtaining a proxy for the responding server object over the network.
</p>
<p>The only other code you need to consider is the code that listens for incoming
messages. This ’runloop’, as it is known, is started by sending a <code>run</code>
message to an instance of the <code>NSRunLoop</code> class. Since an
<code>NSRunLoop</code> object is created automatically for each process, there is no
need to create one yourself. Simply get the default runloop, which is returned
by the <code>+currentRunLoop</code> class method.
</p>
<p>When the runloop detects an incoming message, the message is passed to the
root object of the <code>NSConnection</code>, which performs a method in response to
the message and returns a variable of the appropriate type. The
<code>NSConnection</code> manages all inter-process communication, decoding incoming
messages and encoding any returned values.
</p>
<p>The code to vend the <code>telephoneDirectory</code> object and start the
runloop would look something like this:
</p>
<div class="example">
<pre class="example">/*
* The main() function: Set up the program
* as a 'Distributed Objects Server'.
*/
int main(void)
{
/*
* Remember, create an instance of the
* NSAutoreleasePool class.
*/
CREATE_AUTORELEASE_POOL(pool);
/*
* Get the default NSConnection object
* (a new one is automatically created if none exists).
*/
NSConnection *connXion = [NSConnection defaultConnection];
/*
* Set the responding server object as
* the root object for this connection.
*/
[connXion setRootObject: telephoneDirectory];
/*
* Try to register a name for the NSConnection,
* and report an error if this is not possible.
*/
if ([connXion registerName: @"DirectoryServer"] == NO)
{
NSLog(@"Unable to register as 'DirectoryServer'");
NSLog(@"Perhaps another copy of this program is running?");
exit(1);
}
/* Start the current runloop. */
[[NSRunLoop currentRunLoop] run];
/* Release the pool */
RELEASE(pool);
return 0;
}
</pre></div>
<p>These additional lines of code turn a program into a distributed objects
server, ready to respond to incoming client messages.
</p>
<a name="Code-at-the-Client"></a>
<h4 class="subsection">7.2.2 Code at the Client</h4>
<a name="index-distributed-objects_002c-client-code-1"></a>
<p>At the client, all you need do is obtain a proxy for the responding
server object, using the name that was registered for the <code>NSConnection</code>
at the server.
</p>
<div class="example">
<pre class="example"> /* Create an instance of the NSAutoreleasePool class */
CREATE_AUTORELEASE_POOL(pool);
/* Get the proxy */
id proxy = [NSConnection
rootProxyForConnectionWithRegisteredName: <i>registeredServerName</i>];
/* The rest of your program code goes here */
/* Release the pool */
RELEASE(pool);
</pre></div>
<p>The code that obtains the proxy automatically creates an NSConnection
object for managing the inter-process communication, so there is no need
to create one yourself.
</p>
<p>The above example serves to establish a secure connection between processes
which are run by the same person and are both on the same host.
</p>
<p>If you want your connections to work between different host or between
programs being run by different people, you do this slightly differently,
telling the system that you want to use ’socket’ ports, which make TCP/IP
connections over the network.
</p>
<div class="example">
<pre class="example">int main(void)
{
CREATE_AUTORELEASE_POOL(pool);
/*
* Create a new socket port for your connection.
*/
NSSocketPort *port = [NSSocketPort port];
/*
* Create a connection using the socket port.
*/
NSConnection *connXion = [NSConnection connectionWithReceivePort: port
sendPort: port];
/*
* Set the responding server object as
* the root object for this connection.
*/
[connXion setRootObject: telephoneDirectory];
/*
* Try to register a name for the NSConnection,
* and report an error if this is not possible.
*/
if ([connXion registerName: @"DirectoryServer"
withNameServer: [NSSocketPortNameServer sharedInstance]] == NO)
{
NSLog(@"Unable to register as 'DirectoryServer'");
NSLog(@"Perhaps another copy of this program is running?");
exit(1);
}
[[NSRunLoop currentRunLoop] run];
RELEASE(pool);
return 0;
}
</pre></div>
<p>In the above example, we specify that the socket port name server is used
to register the name for the connection ... this makes the connection name
visible to processes running on other machines.
</p>
<p>The client side code is as follows
</p>
<div class="example">
<pre class="example"> /* Create an instance of the NSAutoreleasePool class */
CREATE_AUTORELEASE_POOL(pool);
/* Get the proxy */
id proxy = [NSConnection
rootProxyForConnectionWithRegisteredName: <i>registeredServerName</i>
host: <i>hostName</i>
usingNameServer: [NSSocketPortNameServer sharedInstance]];
/* The rest of your program code goes here */
/* Release the pool */
RELEASE(pool);
</pre></div>
<p>If the <i>hostName</i> in this statement is ’nil’
or an empty string, then only the local host will be searched to find the
<i>registeredServerName</i>. If <i>hostName</i> is "*", then all hosts on the
local network will be searched.
</p>
<p>In the telephone directory example, the code to obtain the proxy from
any host on the network would be:
</p>
<div class="example">
<pre class="example"> id proxyForDirectory = [NSConnection
rootProxyForConnectionWithRegisteredName: @"DirectoryServer"
host: @"*"
usingNameServer: [NSSocketPortNameServer sharedInstance]];
</pre></div>
<p>With this additional line of code in the client program, you can now
construct a simple Objective-C statement to communicate with the remote
object.
</p>
<div class="example">
<pre class="example"> NSString *wantedNumber = [proxyForDirectory teleNumber: personName];
</pre></div>
<a name="Using-a-Protocol"></a>
<h4 class="subsection">7.2.3 Using a Protocol</h4>
<a name="index-protocol-for-distributed-objects"></a>
<a name="index-distributed-objects_002c-using-a-protocol"></a>
<p>A client process does not need to know the class of a remote server
object to avoid run-time errors, it only needs to know the messages to
which the remote object responds. This can be determined by the client
at run-time, by asking the server if it responds to a particular message
before the message is sent.
</p>
<p>If the methods implemented at the server are stated in a formal
protocol, then the client can ask the server if it conforms to the
protocol, reducing the network traffic required for the individual
message/response requests.
</p>
<p>A further advantage is gained at compile time, when the compiler will
issue a warning if the server fails to implement any method declared in
the protocol, or if the client contains any message to which the server
cannot respond.
</p>
<p>The protocol is saved to a header file and then included in both client
and server programs with the usual compiler <code>#include</code>
directive. Only the server program needs to implement the methods
declared in the protocol. To enable compiler checking in the client
program, extend the type declaration for the proxy to this protocol, and
cast the returned proxy object to the same extended type.
</p>
<p>In the telephone directory example, if the declared protocol was
<code>TelephoneDirectory</code>, declared in header file
<code>protocolHeader.h</code>, then the client code would now look like this:
</p>
<div class="example">
<pre class="example"> #include "protocolHeader.h";
/* Extend the type declaration */
id<TelephoneDirectory> proxyForDirectory;
/* Cast the returned proxy object to the extended type */
proxyForDirectory = (id<TelephoneDirectory>) [NSConnection
rootProxyForConnectionWithRegisteredName: @"DirectoryServer"
usingNameServer: [NSSocketPortNameServer sharedInstance]];
</pre></div>
<p>Since class names and protocol names do not share the same ’address
space’ in a process, the declared protocol and the class of the
responding server object can share the same name, making code easier to
understand.
</p>
<p>For example, <code>proxyForDirectory</code> at the client could be a proxy for
an instance of the <code>TelephoneDirectory</code> class at the server, and
this class could implement the <code>TelephoneDirectory</code> protocol.
</p>
<a name="Complete-Code-for-Telephone-Directory-Application"></a>
<h4 class="subsection">7.2.4 Complete Code for Telephone Directory Application</h4>
<p>Here we provide the rest of the code needed for client and server to actually
run the above example.
</p>
<p><b>Code At Server</b>
</p>
<div class="example">
<pre class="example">#include <Foundation/Foundation.h>
/* Include the TelephoneDirectory protocol header file */
#include "TelephoneDirectory.h"
/*
* Declare the TelephoneDirectory class that
* implements the 'teleNumber' instance method.
*/
@interface TelephoneDirectory : NSObject <TelephoneDirectory>
@end
/*
* Define the TelephoneDirectory class
* and the instance method (teleNumber).
*/
@implementation TelephoneDirectory : NSObject
- (char *) teleNumber: (char *) personName
{
if (strcmp(personName, "Jack") == 0) return " 0123 456";
else if (strcmp(personName, "Jill") == 0) return " 0456 789";
else return " Number not found";
}
@end
/* main() function: Set up the program as a 'Distibuted Objects Server'. */
/* [use code from server example above ...] */
</pre></div>
<p><b>Code at Client</b>
</p>
<div class="example">
<pre class="example">#include <Foundation/Foundation.h>
/* Include the TelephoneDirectory protocol header file */
#include "TelephoneDirectory.h"
/*
* The main() function: Get the telephone number for
* 'personName' from the server registered as 'DirectoryServer'.
*/
int main(int argc, char *argv[])
{
char *personName = argv[1];
char *returnedNumber;
id<TelephoneDirectory> proxyForDirectory;
CREATE_AUTORELEASE_POOL(pool);
/* Acquire the remote reference. */
proxyForDirectory = (id<TelephoneDirectory>) [NSConnection
rootProxyForConnectionWithRegisteredName: @"DirectoryServer"
host: @"*"
usingNameServer: [NSSocketPortNameServer sharedInstance]];
if (proxyForDirectory == nil)
printf("\n** WARNING: NO CONNECTION TO SERVER **\n");
else printf("\n** Connected to server **\n");
if (argc == 2) // Command line name entered
{
returnedNumber = (char *)[proxyForDirectory teleNumber: personName];
printf("\n%s%s%s%s%s\n", "** (In client) The telephone number for ",
personName, " is:",
returnedNumber, " **");
}
else printf("\n** No name entered **\n");
printf("\n%s\n\n", "** End of client program **");
RELEASE(pool);
return 0;
}
</pre></div>
<p>To get this running, all you need do is create two directories, one for the
client and one for the server. Each directory will hold a makefile, the client
or server source code, and a copy of the protocol header file. When the files
compile, first run the server and then the client. You can try this on the
same machine, or on two different machines (with GNUstep installed) on the
same LAN. What happens when you run the client without the server? How would
you display a "No Server Connection" warning at the client?
</p>
<a name="GNUstep-Distributed-Objects-Name-Server"></a>
<h4 class="subsection">7.2.5 GNUstep Distributed Objects Name Server</h4>
<a name="index-gdomap"></a>
<a name="index-Distributed-Objects-Name-Server_002c-GNUstep"></a>
<p>You might wonder how the client finds the server, or, rather, how it finds the
directory the server lists itself in.
</p>
<p>For the default connection type (a connection only usable on the local host
between processes run by the same person), a private file (or the registry
on ms-windows) is used to hold the name registration information.
</p>
<p>For connections using socket ports to communicate between hosts,
an auxiliary process will
automatically be started on each machine, if it isn’t running already, that
handles this, allowing the server to register and the client to send a query
behind the scenes. This <i>GNUstep Distributed Objects Name Server</i> runs as
’<code>gdomap</code>’ and binds to port 538. See the manual page or the HTML
“GNUstep Base Tools” <a href="../../Tools/Reference/index.html">documentation</a> for further information.
</p>
<a name="Look-Ma_002c-No-Stubs_0021"></a>
<h4 class="subsection">7.2.6 Look Ma, No Stubs!</h4>
<p>One difference you may have noticed in the example we just looked at from
other remote method invocation interfaces such as CORBA and Java RMI was that
there are <i>no stub classes</i>. The source of this great boon is described at
the end of this chapter: <a href="#Distributed-Objects">Language Support for
Distributed Objects</a>.
</p>
<a name="A-More-Involved-Example"></a>
<h3 class="section">7.3 A More Involved Example</h3>
<a name="index-distributed-objects_002c-example-_0028no-error-checking_0029"></a>
<a name="index-game-server-example"></a>
<p>Now we will look at an example called GameServer that uses distributed objects
in a client/server game.
</p>
<p>Actually the game itself is not implemented, just its distributed support
structure, and while the code to vend an object and connect to a remote
process is similar to that already shown, the code does show a number of
additional techniques that can be used in other client/server programs. Here
are the requirements we will implement:
</p>
<ul>
<li> When the client attempts to join the game, the server checks that the client
is entitled to join, based on the last time the client played. The rule is:
if the client lost the last game, then they cannot re-play for the next 2
hours; but if the client won the last game, then they can re-play the game at
any time (a reward for winning).<br>
</li><li> The server also makes sure the client is not already connected and playing the
game (i.e. they cannot play two games at the same time - that would be
cheating).<br>
</li><li> In addition to a proxy for the server being obtained at the client, a proxy
for the client is received at the server. This allows two-way messaging, where
the client can send messages to the server and the server can send messages to
the client (e.g. the state of play may be affected by the actions of other
players, or by other events at the server).<br>
<p>Two protocols will therefore be required, one for the methods
implemented at the server and one for those implemented at the client.
</p></li></ul>
<p>Have a look at the program code in the following sections and added
comments. Can you work out what is happening at the server and client? If you
have any difficulties then refer to the relevant sections in this manual, or
to class documentation <a href="../Reference/index.html">here</a> or at the Apple
web site.
</p>
<a name="Protocol-Adopted-at-Client"></a>
<h4 class="subsection">7.3.1 Protocol Adopted at Client</h4>
<p>We have chosen <code>GameClient</code> as the name of both the protocol
adopted at the client and the class of the responding client object. The
header file declaring this protocol will simply declare the methods that
the class must implement.
</p>
<div class="example">
<pre class="example">@protocol GameClient
- (void) clientMessage: (bycopy NSString *)theMessage;
- (int) clientReply;
// Other methods would be added that
// reflect the nature of the game.
@end
</pre></div>
<p>The protocol will be saved as <code>GameClient.h</code>.
</p>
<a name="Protocol-Adopted-at-Server"></a>
<h4 class="subsection">7.3.2 Protocol Adopted at Server</h4>
<p>We have chosen <code>GameServer</code> as the name of both the protocol
adopted at the server and the class of the responding server object. The
header file declaring this protocol will simply declare the methods that
the class must implement.
</p>
<div class="example">
<pre class="example">@protocol GameServer
- (BOOL) mayJoin: (id)client asPlayer: (bycopy NSString*)name;
- (int) startGame: (bycopy NSString*)name;
- (BOOL) endGame: (bycopy NSString*)name;
// Other methods would be added that
// reflect the nature of the game.
@end
</pre></div>
<p>The protocol will be saved as <code>GameServer.h</code>.
</p>
<a name="Code-at-the-Client-1"></a>
<h4 class="subsection">7.3.3 Code at the Client</h4>
<p>The client code contains the <code>main</code> function and the
<code>GameClient</code> class declaration and implementation.
</p>
<p>The <code>main()</code> function attempts to connect to the server, while the
<code>GameClient</code> class adopts the <code>GameClient</code> protocol.
</p>
<div class="example">
<pre class="example">#include <Foundation/Foundation.h>
#include "GameServer.h"
#include "GameClient.h"
/*
* GameClient class declaration:
* Adopt the GameClient protocol.
*/
@interface GameClient : NSObject <GameClient>
@end
/*
* GameClient class implementation.
*/
@implementation GameClient
/*
* Implement clientMessage: as declared in the protocol.
* The method simply prints a message at the client.
*/
- (void) clientMessage: (NSString*)theMessage
{
printf([theMessage cString]);
}
/*
* Implement clientReply: as declared in the protocol.
* The method simply returns the character entered
* at the client keyboard.
*/
- (int) clientReply
{
return getchar();
}
@end // End of GameClient class implementation.
/*
* The main function of the client program.
*/
int main(int argc, char **argv)
{
CREATE_AUTORELEASE_POOL(pool);
id<GameServer> server;
int result;
NSString *name;
id client;
/*
* The NSUserName() function returns the name of the
* current user, which is sent to the server when we
* try to join the game.
*/
name = NSUserName();
/*
* Create a GameClient object that is sent to
* the server when we try to join the game.
*/
client = AUTORELEASE([GameClient new]);
/*
* Try to get a proxy for the root object of a server
* registered under the name 'JoinGame'. Since the host
* is '*', we can connect to any server on the local network.
*/
server = (id<GameServer>)[NSConnection
rootProxyForConnectionWithRegisteredName: @"JoinGame"
host: @"*"
usingNameServer: [NSSocketPortNameServer sharedInstance]];
if (server == nil)
{
printf("\n** No Connection to GameServer **\n");
result = 1;
}
/*
* Try to join the game, passing a GameClient object as
* the client, and our user-name as name. The 'client'
* argument will be received as a proxy at the server.
*/
else if ([server mayJoin: client asPlayer: name] == NO)
{
result = 1; // We cannot join the game.
}
else
{
/*
* At this point, we would actually start to play the game.
*/
[server startGame: name]; // Start playing game.
[server endGame: name]; // Finally end the game.
result = 0;
}
RELEASE(pool);
return result;
}
</pre></div>
<p>To summarise the code at the client:
</p>
<ul>
<li> We obtained a proxy for the server and can now communicate with the server
using the methods declared in the <code>GameServer</code> protocol.<br>
</li><li> We passed a <code>GameClient</code> object and our user-name to the server (the
<code>GameClient</code> object is received as a proxy at the server). The server
can now communicate with the client using the methods declared in the
<code>GameClient</code> protocol.<br>
</li><li> When the game is in progress, the server can alter the state of the client
object to reflect the success of the player.
</li></ul>
<a name="Code-at-the-Server-1"></a>
<h4 class="subsection">7.3.4 Code at the Server</h4>
<p>The server code contains the <code>main</code> function and the
<code>GameServer</code> class declaration and implementation.
</p>
<p>The <code>main()</code> function vends the server’s root object and starts the
runloop, while the <code>GameServer</code> class adopts the <code>GameServer</code>
protocol. The class also implements methods that initialise and
deallocate the root object’s instance variables (dictionaries that hold
player information).
</p>
<div class="example">
<pre class="example">#include <Foundation/Foundation.h>
#include "GameServer.h"
#include "GameClient.h"
/*
* GameServer class declaration:
* Adopt the GameServer protocol and declare
* GameServer instance variables.
*/
@interface GameServer : NSObject <GameServer>
{
NSMutableDictionary *delayUntil; // Delays to re-joining GameServer.
NSMutableDictionary *currentPlayers; // Proxies to each client.
NSMutableDictionary *hasWon; // Success in game for each player.
}
@end
/*
* GameServer class implementation.
*/
@implementation GameServer
/* Initialise GameServer's instance variables. */
- (id) init
{
self = [super init];
if (self != nil)
{
/*
* Create a dictionary for a maximum of
* 10 named players that will hold a
* re-joining time delay.
*/
delayUntil = [[NSMutableDictionary alloc]
initWithCapacity: 10];
/*
* Create a dictionary that will hold the
* names of these players and a proxy for
* the received client objects.
*/
currentPlayers = [[NSMutableDictionary alloc]
initWithCapacity: 10];
/*
* Create a dictionary that will record
* a win for any of these named players.
*/
hasWon = [[NSMutableDictionary alloc]
initWithCapacity: 10];
}
return self;
}
/* Release GameServer's instance variables. */
- (void) dealloc
{
RELEASE(delayUntil);
RELEASE(currentPlayers);
RELEASE(hasWon);
[super dealloc];
}
/*
* Implement mayJoin:: as declared in the protocol.
* Adds the client to the list of current players.
* Each player is represented at the server by both
* name and by proxy to the received client object.
* A player cannot join the game if they are already playing,
* or if joining has been delayed until a later date.
*/
- (BOOL) mayJoin: (id)client asPlayer: (NSString*)name
{
NSDate *delay; // The time a player can re-join the game.
NSString *aMessage;
if (name == nil)
{
NSLog(@"Attempt to join nil user");
return NO;
}
/* Has the player already joined the game? */
if ([currentPlayers objectForKey: name] != nil)
{
/* Inform the client that they cannot join. */
aMessage = @"\nSorry, but you are already playing GameServer!\n";
[client clientMessage: aMessage];
return NO;
}
/* Get the player's time delay for re-joining. */
delay = [delayUntil objectForKey: name];
/*
* Can the player join the game? Yes if there is
* no restriction or if the time delay has passed;
* otherwise no, they cannot join.
*/
if (delay == nil || [delay timeIntervalSinceNow] <= 0.0)
{
/* Remove the old restriction on re-joining the game. */
[delayUntil removeObjectForKey: name];
/* Add the player to the list of current players. */
[currentPlayers setObject: client forKey: name];
[hasWon setObject: @"NO" forKey: name]; // They've not won yet.
/* Inform the client that they have joined the game. */
aMessage = @"\nWelcome to GameServer\n";
[client clientMessage: aMessage];
return YES;
}
else
{
/* Inform the client that they cannot re-join. */
aMessage = @"\nSorry, you cannot re-join GameServer yet.\n";
[client clientMessage: aMessage];
return NO;
}
}
/*
* Implement startGame: as declared in the protocol.
* Simply ask the player if they want to win, and get
* there reply.
*/
- (int) startGame: (NSString *)name
{
NSString *aMessage;
id client;
int reply;
client = [currentPlayers objectForKey: name];
aMessage = @"\nDo you want to win this game? (Y/N <RET>) ... ";
[client clientMessage: aMessage];
reply = [client clientReply];
if (reply == 'y' || reply == 'Y')
[hasWon setObject: @"YES" forKey: name]; // They win.
else [hasWon setObject: @"NO" forKey: name]; // They loose.
return 0;
}
/*
* Implement endGame: as declared in the protocol.
* Removes a player from the game, and either sets
* a restriction on the player re-joining or removes
* the current restriction.
*/
- (BOOL) endGame: (NSString*)name
{
id client;
NSString *aMessage, *yesOrNo;
NSDate *now, *delay;
NSTimeInterval twoHours = 2 * 60 * 60; // Seconds in 2 hours.
if (name == nil)
{
NSLog(@"Attempt to end nil user");
return NO;
}
now = [NSDate date];
delay = [now addTimeInterval: twoHours];
client = [currentPlayers objectForKey: name];
yesOrNo = [hasWon objectForKey: name];
if ([yesOrNo isEqualToString: @"YES"]) // Has player won?
{
/*
* Player wins, no time delay to re-joining the game.
* Remove any re-joining restriction and send
* a message to the client.
*/
[delayUntil removeObjectForKey: name];
aMessage = @"\nWell played: you can re-join GameServer at any time.\n";
[client clientMessage: aMessage];
}
else // Player lost
{
/*
* Set a time delay for re-joining the game,
* and send a message to the client.
*/
[delayUntil setObject: delay forKey: name];
aMessage = @"\nYou lost, but you can re-join GameServer in 2 hours.\n";
[client clientMessage: aMessage];
}
/* Remove the player from the current game. */
[currentPlayers removeObjectForKey: name];
[hasWon removeObjectForKey: name];
return YES;
}
@end // End of GameServer class implementation
/*
* The main function of the server program simply
* vends the root object and starts the runloop.
*/
int main(int argc, char** argv)
{
CREATE_AUTORELEASE_POOL(pool);
GameServer *server;
NSSocketPort *port;
NSConnection *connXion;
server = AUTORELEASE([GameServer new]);
port = [NSSocketPort port];
connXion = [NSConnection connectionWithReceivePort: port sendPort: port];
[connXion setRootObject: server];
[connXion registerName: @"JoinGame"
withNameServer: [NSSocketPortNameServer sharedInstance]];
[[NSRunLoop currentRunLoop] run];
RELEASE(pool);
return 0;
}
</pre></div>
<p>To summarise the code at the server:
</p>
<ul>
<li> We vend the server’s root object and start a runloop, allowing clients to
connect with the server.<br>
</li><li> When we receive a proxy for a client object, we communicate with that client
using methods declared in the <code>ClientServer</code> protocol.<br>
</li><li> We create three dictionary objects, each referenced by player
name. <code>currentUsers</code> holds proxies for each of the current players;
<code>delayUntil</code> holds times when each player can re-join the game; and
<code>hasWon</code> holds a string for each player, which is set to "YES" if the
player wins.<br>
</li><li> When the game is in progress, the server can alter the state of each client
object to reflect the success of each player.
</li></ul>
<p>I hope you managed to understand most of the code in this example. If
you are reading the on-screen version, then you can copy and paste the
code to suitably named files, create makefiles, and then make and run
each program. What message is displayed if you immediately try to
re-join a game after losing? And after winning?
</p>
<p><i>Exercise: Modify the server code so that the server records the
number of wins for each player, and displays this information at both
the start and end of each game.</i>
</p>
<a name="Language-Support-for-Distributed-Objects"></a>
<h3 class="section">7.4 Language Support for Distributed Objects</h3>
<p>Objective-C provides special ’type’ qualifiers that can be used in a
protocol to control the way that message arguments are passed between
remote processes, while at run time, the run-time system transparently
uses what is known as ’forward invocation’ to forward messages to a
remote process. (See <a href="Advanced-Messaging.html#Advanced-Messaging">Forwarding</a>.)
</p>
<a name="Protocol-Type-Qualifiers"></a>
<h4 class="subsection">7.4.1 Protocol Type Qualifiers</h4>
<a name="index-protocol-type-qualifiers"></a>
<a name="index-in_002c-out_002c-and-inout-type-qualifiers"></a>
<a name="index-out_002c-type-qualifier"></a>
<a name="index-oneway_002c-type-qualifier"></a>
<a name="index-bycopy-and-byref-type-qualifiers"></a>
<p>When message arguments are passed by value then the receiving method can
only alter the copy it receives, and not the value of the original
variable. When an argument is passed by reference (as a pointer), the
receiving method has access to the original variable and can alter that
variable’s data. In this case the argument is effectively passed ’in’ to
the method, and then passed ’out’ of the method (on method return).
</p>
<p>When an argument is passed by reference to a remote object, the network
must handle this two-way traffic, whether or not the remote object
modifies the received argument.
</p>
<p>Type qualifiers can be used in a protocol to control the way these
messages are handled, and to indicate whether or not the sending process
will wait for the remote process to return.
</p>
<ul>
<li> The <b>oneway</b> qualifier is used in conjunction with a
<code>void</code> return type to inform the run-time system that the sending
process does not need to wait for the receiving method to return (known
as ’asynchronous’ messaging). The protocol declaration for the receiving
method would look something like this:<br><br>
<p><code>- (<b>oneway</b> void)noWaitForReply;</code><br><br>
</p>
</li><li> The <b>in, out </b> and <b>inout</b> qualifiers can be used with pointer
arguments to control the direction in which an argument is passed. The
protocol declaration for the receiving methods would look something like
this:<br>
<div class="example">
<pre class="example">/*
* The value that 'number' points to will be passed <b>in</b> to the remote process.
* (No need to return the argument's value from the remote process.)
*/
<code>- setValue: (<b>in</b> int *)number;</code>
/*
* The value that 'number' points to will be passed <b>out</b> of the remote process.
* (No need to send the argument's value to the remote process.)
*/
<code>- getValue: (<b>out</b> int *)number;</code>
/*
* The value that 'number' points to is first passed <b>in</b> to the remote
* process, but will eventually be the value that is passed <b>out</b> of the
* remote process. (Send and return the argument's value.)
*/
<code>- changeValue: (<b>inout</b> int *)number;</code>
</pre></div>
<p>Passing of arguments by reference is very restricted in Objective-C.
it applies only to pointers to C data types, not to objects, and except
for the special case of a pointer to a nul terminated C string (<b>char*</b>)
the pointer is assumed to refer to a single data item of the specified
type.
</p>
<div class="example">
<pre class="example">/*
* A method passing an unsigned short integer by reference.
*/
<code>- updateCounter: (<b>inout</b> unsigned shortn *)value;</code>
/*
* A method passing a structure by reference.
*/
<code>- updateState: (<b>inout</b> struct stateInfo *)value;</code>
/*
* As a special case, a char (or equivalent typedef) passed by reference
* is assumed to be a nul terminated string ... there is no way to pass
* a single character by reference:
*/
<code>- updateBuffer: (<b>inout</b> char *)str;</code>
</pre></div>
</li><li> The <b>bycopy</b> and <b>byref</b> qualifiers can be used in a protocol
when the argument or return type is an object.<br><br>
<p>An object is normally passed by reference and received in the remote
process as a proxy. When an object is passed by copy, then a copy of
the object will be received in the remote process, allowing the remote
process to directly interact with the copy. Protocol declarations would
look something like this:<br>
</p>
<div class="example">
<pre class="example">/*
* Copy of object will be received in the remote process.
*/
- sortNames: (<b>bycopy</b> id)listOfNames;
/*
* Copy of object will be returned by the remote process.
*/
- (<b>bycopy</b> id)returnNames;
</pre></div>
<p>By default, large objects are normally sent <b>byref</b>, while small
objects like <code>NSStrings</code> are normally sent <b>bycopy</b>, but you
cannot rely on these defaults being adopted and should explicitly state
the qualifier in the protocol.<br><br>
</p>
<p>The <b>bycopy</b> qualifier can also be used in conjunction with the
<b>out</b> qualifier, to indicate that an object will be passed <b>out</b> of
the remote process by copy rather than by proxy (no need to send the
object).<br>
</p>
<div class="example">
<pre class="example">/*
* The object will not be received in the remote process, but the object
* will be returned <b>bycopy</b>.
*/
- sortAndReturn: (<b>bycopy out</b> id *)listOfNames;
</pre></div>
<p>You should be aware that some classes ignore the <b>bycopy</b> qualifier
and the object will be sent by reference. The <b>bycopy</b> qualifier will
also be ignored if the remote process does not have the class of the
object in its address space, since an object’s instance variables are
accessed through the object’s methods.<br><br>
</p>
<p>When a copy of an object is sent to a remote process, only the object’s
instance variables are sent and received (an object’s methods exist in
the address space of the object’s class, not in the address space of the
individual object).
</p>
</li></ul>
<a name="Message-Forwarding"></a>
<h4 class="subsection">7.4.2 Message Forwarding</h4>
<a name="index-message-forwarding_002c-distributed-objects"></a>
<a name="index-forward-invocation_002c-distributed-objects"></a>
<p>If you have used other remote invocation mechanisms such as CORBA or Java
RMI, you may have noticed a big difference from these in the GNUstep
Distributed Object paradigm – there are no “stub” classes, either on the
client or the server. This tremendously simplifies the use of remote
invocation and is possible due to the Objective-C message-forwarding facility
(<a href="Advanced-Messaging.html#Advanced-Messaging">Forwarding</a>).
</p>
<p>In GNUstep, there are proxies on the client and server side that handle
network communications and serialization/deserialization of arguments and
return values just as in CORBA and RMI, but when it comes to responding to the
client and server protocol method calls themselves, they are intercepted
through the use of the <code>forwardInvocation:</code> method, where they can be
passed on to the registered client and server objects through the ordinary
Objective-C message sending mechanism.
</p>
<a name="Error-Checking"></a>
<h3 class="section">7.5 Error Checking</h3>
<a name="index-error-checking_002c-distributed-objects"></a>
<a name="index-distributed-objects_002c-error-checking"></a>
<p>When dealing with distributed objects your code must be able to handle
the following situations: failure to vend the server object, exceptions
raised at run-time, and failure of the network connection.
</p>
<a name="Vending-the-Server-Object"></a>
<h4 class="subsection">7.5.1 Vending the Server Object</h4>
<p>When vending the server object, your code must be able to handle the
situation in which the network does not accept the proposed registered
name for the server.
</p>
<a name="Catching-Exceptions"></a>
<h4 class="subsection">7.5.2 Catching Exceptions</h4>
<p>There are two situations to consider.
</p><ul>
<li> An <code>NSPortTimeoutException</code> is raised.<br><br>
This exception is raised if a message takes too long to arrive at the
remote process, or if a reply takes too long to return. This will happen
if the remote process is busy, has hung, or if there is a problem with
the network. The best way to handle the exception is to close the
connection to the remote process.<br><br>
</li><li> An exception is raised in the remote process while the remote
process is executing a method.<br><br>
In most cases you can deal directly with these exceptions in the process
in which they were raised; i.e. without having to consider the network
connection itself.
</li></ul>
<a name="The-Connection-Fails"></a>
<h4 class="subsection">7.5.3 The Connection Fails</h4>
<p>You can register an observer object to receive a notification, in the
form of a <code>connectionDidDie:</code> message, when a registered connection
fails. The argument to this message will be an <code>NSNotification</code>
object that returns the failed connection when it receives an
<code>object</code> message. See <a href="Base-Library.html#Base-Library">Event-Based Communications</a>
for more information on notifications.
</p>
<p>To receive this ’notification’ the observer must implement the
<code>connectionDidDie:</code> method, but can be an instance of any class. The
observer can then handle the failure gracefully, by releasing any
references to the failed connection and releasing proxies that used the
connection. Registering an object to receive this notification is
described in more detail in the <code>NSConnection</code> class documentation.
</p>
<hr>
<div class="header">
<p>
Next: <a href="Base-Library.html#Base-Library" accesskey="n" rel="next">Base Library</a>, Previous: <a href="Exception-Handling.html#Exception-Handling" accesskey="p" rel="prev">Exception Handling</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Make.html#Make" title="Index" rel="index">Index</a>]</p>
</div>
</body>
</html>
|