Writing an Ice Application with Objective-C

This page shows how to create an Ice application with Objective-C.

On this page:

Compiling a Slice Definition for Objective-C

The first step in creating our Objective-C application is to compile our Slice definition to generate Objective-C proxies and skeletons. You can compile the definition as follows:

slice2objc Printer.ice

The slice2objc compiler produces two Objective-C source files from this definition, Printer.h and Printer.m.

  • Printer.h
    The Printer.h header file contains Objective-C type definitions that correspond to the Slice definitions for our Printer interface. This header file must be included in both the client and the server source code.
  • Printer.m
    The Printer.m file contains the source code for our Printer interface. The generated source contains type-specific run-time support for both clients and servers. For example, it contains code that marshals parameter data (the string passed to the printString operation) on the client side and unmarshals that data on the server side.
    The Printer.m file must be compiled and linked into both client and server.

Writing and Compiling a Server in Objective-C

The source code for the server takes only a few lines and is shown in full here:

Objective-C
#import <objc/Ice.h>
#import <Printer.h>
#import <stdio.h>

@interface PrinterI : DemoPrinter <DemoPrinter>
@end

@implementation PrinterI
-(void) printString:(NSMutableString *)s current:(ICECurrent *)current
{
    printf("%s\n", [s UTF8String]);
    fflush(stdout);
}
@end

int
main(int argc, char* argv[])
{
    int status = EXIT_FAILURE;
    @autoreleasepool
    {
        id<ICECommunicator> communicator = nil;
        @try
        {
            communicator = [ICEUtil createCommunicator:&argc argv:argv];
            id<ICEObjectAdapter> adapter = [communicator createObjectAdapterWithEndpoints:@"SimplePrinterAdapter"
                                                                                endpoints:@"default -p 10000"];
            [adapter add:[PrinterI printer] identity:[ICEUtil stringToIdentity:@"SimplePrinter"]];
            [adapter activate];

            [communicator waitForShutdown];

            status = EXIT_SUCCESS;
        }
        @catch(NSException* ex)
        {
            NSLog(@"%@", ex);
        }

        [communicator destroy];
    }
    return status;
}


Every Ice source file starts with an include directive for objc/Ice.h, which contains the definitions for the Ice run time. We also include Printer.h, which was generated by the Slice compiler and contains the Objective-C definitions for our printer interface:

Objective-C
#import <objc/Ice.h>
#import <Printer.h>
#import <stdio.h>

Our server implements a single printer servant, of type PrinterI. Looking at the generated code in Printer.h, we find the following (tidied up a little to get rid of irrelevant detail):

Objective-C
@protocol DemoPrinter <ICEObject>
-(void) printString:(NSMutableString *)s
            current:(ICECurrent *)current;
@end

@interface DemoPrinter : ICEObject
// ...
@end

The DemoPrinter protocol and class definitions are generated by the Slice compiler. The protocol defines the printString method, which we must implement in our servant. The DemoPrinter class contains methods that are internal to the mapping, so we are not concerned with these. However, our servant must derive from this skeleton class:

Objective-C
@interface PrinterI : DemoPrinter <DemoPrinter>
@end

@implementation PrinterI
-(void) printString:(NSMutableString *)s current:(ICECurrent *)current
{
    printf("%s\n", [s UTF8String]);
    fflush(stdout);
}
@end

As you can see, the implementation of the printString method is trivial: it simply writes its string argument to stdout.

Note that printString has a second parameter of type ICECurrent. The Ice run time passes additional information about an incoming request to the servant in this parameter. For now, we will ignore it.

What follows is the server main program. Note the general structure of the code:

Objective-C
int
main(int argc, char* argv[])
{
    int status = EXIT_FAILURE;
    @autoreleasepool
    {
        id<ICECommunicator> communicator = nil;
        @try
        {
            communicator = [ICEUtil createCommunicator:&argc argv:argv];

            // Server implementation here...

            status = EXIT_SUCCESS;
        }
        @catch(NSException* ex)
        {
            NSLog(@"%@", ex);
        }

        [communicator destroy];
    }
    return status;
}

The body of main instantiates an autorelease pool, which it releases before returning to ensure that the program does not leak memory. main contains the declaration of two variables, status and communicator. The status variable contains the exit status of the program and the communicator variable, of type id<ICECommunicator>, contains the main handle to the Ice run time.

Following these declarations is a try block in which we place all the server code, followed by a catch handler that logs any unhandled exceptions.

Before returning, main executes a bit of cleanup code that calls the destroy method on the communicator. The cleanup call is outside the try block for a reason: we must ensure that the Ice run time is finalized whether the code terminates normally or terminates due to an exception.

Failure to call destroy on the communicator before the program exits results in undefined behavior.

The body of the try block contains the actual server code:

Objective-C
            communicator = [ICEUtil createCommunicator:&argc argv:argv];
            id<ICEObjectAdapter> adapter = [communicator createObjectAdapterWithEndpoints:@"SimplePrinterAdapter"
                                                                                endpoints:@"default -p 10000"];
            [adapter add:[PrinterI printer] identity:[ICEUtil stringToIdentity:@"SimplePrinter"]];
            [adapter activate];

            [communicator waitForShutdown];

The code goes through the following steps:

  1. We initialize the Ice run time by calling createCommunicator. (We pass argc and argv to this call because the server may have command-line arguments that are of interest to the run time; for this example, the server does not require any command-line arguments.) The call to createCommunicator returns a value of type id<ICECommunicator>, which is the main object in the Ice run time.
  2. We create an object adapter by calling createObjectAdapterWithEndpoints on the Communicator instance. The arguments we pass are "SimplePrinterAdapter" (which is the name of the adapter) and "default -p 10000", which instructs the adapter to listen for incoming requests using the default transport protocol (TCP/IP) at port number 10000.
  3. At this point, the server-side run time is initialized and we create a servant for our Printer interface by instantiating a PrinterI object.
  4. We inform the object adapter of the presence of a new servant by calling add on the adapter; the arguments to add are the servant we have just instantiated, plus an identifier. In this case, the string "SimplePrinter" is the name of the Ice object. (If we had multiple printers, each would have a different name or, more correctly, a different object identity.)
  5. Next, we activate the adapter by calling its activate method. (The adapter is initially created in a holding state; this is useful if we have many servants that share the same adapter and do not want requests to be processed until after all the servants have been instantiated.) The server starts to process incoming requests from clients as soon as the adapter is activated.
  6. Finally, we call waitForShutdown. This call suspends the calling thread until the server is shut down. (For now, we will simply interrupt the server on the command line when we no longer need it, which terminates the server immediately.)

Assuming that we have the server code in a file called Server.m, we can compile it as follows:

c++ -c -I. -I$ICE_HOME/include Printer.m Server.m

This compiles both our application code and the code that was generated by the Slice compiler. We assume that the ICE_HOME environment variable is set to the top-level directory containing the Ice run time. (For example, if you have installed Ice in /opt/ice, set ICE_HOME to that path.) Depending on your platform, you may have to add additional include directives or other options to the compiler; please see the demo programs that ship with Ice for the details.

Finally, we need to link the server into an executable:

c++ Printer.o Server.o -o server -L$ICE_HOME/lib -lIceObjC -framework Foundation

Again, depending on the platform, the actual list of libraries you need to link against may be longer. The demo programs that ship with Ice contain all the details.

Writing and Compiling a Client in Objective-C

The client code looks very similar to the server. Here it is in full:

Objective-C
#import <objc/Ice.h>
#import <Printer.h>
#import <stdio.h>

int
main(int argc, char* argv[])
{
    int status = EXIT_FAILURE;
    @autoreleasepool
    {
        id<ICECommunicator> communicator = nil;
        @try
        {
            communicator = [ICEUtil createCommunicator:&argc argv:argv];
            id<ICEObjectPrx> base = [communicator stringToProxy:@"SimplePrinter:default -p 10000"];
            id<DemoPrinterPrx> printer = [DemoPrinterPrx checkedCast:base];
            if(!printer)
            {
                [NSException raise:@"Invalid proxy" format:@""];
            }
            [printer printString:@"Hello World!"];
            status = EXIT_SUCCESS;
        }
        @catch(NSException* ex)
        {
            NSLog(@"%@", ex);
        }

        [communicator destroy];
    }
    return status;
}

Note that the overall code layout is the same as for the server: we include the headers for the Ice run time and the header generated by the Slice compiler, and we use the same try block and catch handlers to deal with errors.

The code in the try block does the following:

  1. As for the server, we initialize the Ice run time by calling createCommunicator.
  2. The next step is to obtain a proxy for the remote printer. We create a proxy by calling stringToProxy on the communicator, with the string "SimplePrinter:default -p 10000". Note that the string contains the object identity and the port number that were used by the server. (Obviously, hard-coding object identities and port numbers into our applications is a bad idea, but it will do for now; we will see more architecturally sound ways of doing this when we discuss IceGrid.)
  3. The proxy returned by stringToProxy is of type id<ICEObjectPrx>, which is at the root of the inheritance tree for interfaces. But to actually talk to our printer, we need a proxy for a Printer interface, not an Object interface. To do this, we need to do a down-cast by calling the checkedCast class method on the DemoPrinterPrx class. A checked cast sends a message to the server, effectively asking "is this a proxy for a Printer interface?" If so, the call returns a proxy to a Printer; otherwise, if the proxy denotes an interface of some other type, the call returns a null proxy.
  4. We test that the down-cast succeeded and, if not, throw an error message that terminates the client.
  5. We now have a live proxy in our address space and can call the printString method, passing it the time-honored "Hello World!" string. The server prints that string on its terminal.

Compiling and linking the client looks much the same as for the server:

c++ -c -I. -I$ICE_HOME/include Printer.m Client.m
c++ Printer.o Client.o -o client -L$ICE_HOME/lib -lIceObjC -framework Foundation

Running Client and Server in Objective-C

To run client and server, we first start the server in a separate window:

./server

At this point, we won't see anything because the server simply waits for a client to connect to it. We run the client in a different window:

./client

The client runs and exits without producing any output; however, in the server window, we see the "Hello World!" that is produced by the printer. To get rid of the server, we interrupt it on the command line for now.

If anything goes wrong, the client will print an error message. For example, if we run the client without having first started the server, we get:

Network.cpp:1218: Ice::ConnectionRefusedException:
connection refused: Connection refused

Note that, to successfully run client and server, you may have to set DYLD_LIBRARY_PATH to include the Ice library directory. Please see the installation instructions and the demo applications that ship with Ice Touch for details.

See Also