Writing an Ice Application with C++ (C++11)
This page shows how to create an Ice application with C++ using the Ice C++11 mapping.
On this page:
Compiling a Slice Definition for C++
The first step in creating our C++ application is to compile our Slice definition to generate C++ proxies and skeletons. You can compile the definition as follows:
slice2cpp Printer.ice
The slice2cpp
compiler produces two C++ source files from this definition, Printer.h
and Printer.cpp
.
Printer.h
ThePrinter.h
header file contains C++ type definitions that correspond to the Slice definitions for ourPrinter
interface. This header file must be included in both the client and the server source code.
Printer.cpp
ThePrinter.cpp
file contains the source code for ourPrinter
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 theprintString
operation) on the client side and unmarshals that data on the server side.
ThePrinter.cpp
file must be compiled and linked into both client and server.
Writing and Compiling a Server in C++
The source code for the server takes only a few lines and is shown in full here:
#include <Ice/Ice.h> #include <Printer.h> using namespace std; using namespace Demo; class PrinterI : public Printer { public: virtual void printString(string s, const Ice::Current&) override; }; void PrinterI::printString(string s, const Ice::Current&) { cout << s << endl; } int main(int argc, char* argv[]) { try { Ice::CommunicatorHolder ich(argc, argv); auto adapter = ich->createObjectAdapterWithEndpoints("SimplePrinterAdapter", "default -p 10000"); auto servant = make_shared<PrinterI>(); adapter->add(servant, Ice::stringToIdentity("SimplePrinter")); adapter->activate(); ich->waitForShutdown(); } catch(const std::exception& e) { cerr << e.what() << endl; return 1; } return 0; }
Every Ice source file starts with an include directive for 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 C++ definitions for our printer interface, and we import the contents of the std
and Demo
namespaces for brevity in the code that follows:
#include <Ice/Ice.h> #include <Printer.h> using namespace std; using namespace Demo;
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):
namespace Demo { class Printer : public virtual Ice::Object { public: virtual void printString(std::string, const Ice::Current&) = 0; }; }
The Printer
skeleton class definition is generated by the Slice compiler. (Note that the printString
method is pure virtual so the skeleton class cannot be instantiated.) Our servant class inherits from the skeleton class to provide an implementation of the pure virtual printString
method. (By convention, we use an I
-suffix to indicate that the class implements an interface.)
class PrinterI : public Printer { public: virtual void printString(string s, const Ice::Current&) override; };
The implementation of the printString
method is trivial: it simply writes its string argument to stdout
:
void PrinterI::printString(string s, const Ice::Current&) { cout << s << endl; }
Note that printString
has a second parameter of type Ice::Current
. As you can see from the definition of Printer::printString
, the Slice compiler generates a default argument for this parameter, so we can leave it unused in our implementation. (We will examine the purpose of the Ice::Current
parameter later.)
What follows is the server main program. Note the general structure of the code:
int main(int argc, char* argv[]) { try { Ice::CommunicatorHolder ich(argc, argv); // Server implementation here ... } catch(const std::exception& e) { cerr << e.what() << endl; return 1; } return 0; }
The body of main
contains a try/catch block, and we start by creating an Ice CommunicatorHolder
on the stack. We pass argc
and argv
to the CommunicatorHolder
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.
Next, we have the actual server code:
auto adapter = ich->createObjectAdapterWithEndpoints("SimplePrinterAdapter", "default -p 10000"); auto servant = make_shared<PrinterI>(); adapter->add(servant, icHolder->stringToIdentity("SimplePrinter")); adapter->activate(); ich->waitForShutdown();
The code goes through the following steps:
- We create an object adapter by calling
createObjectAdapterWithEndpoints
on theCommunicator
instance (throughCommunicatorHolder'
s overloaded arrowoperator
). 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. - At this point, the server-side run time is initialized and we create a servant for our
Printer
interface by instantiating aPrinterI
object. - We inform the object adapter of the presence of a new servant by calling
add
on the adapter; the arguments toadd
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.) - 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. - 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.cpp
, we can compile it as follows:
c++ -I. -DICE_CPP11_MAPPING -c Printer.cpp Server.cpp
This compiles both our application code and the code that was generated by the Slice compiler. 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.
-DICE_CPP11_MAPPING
enables the new Ice C++11 mapping
Finally, we need to link the server into an executable:
c++ -o server Printer.o Server.o -lIce++11
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 detail.
Writing and Compiling a Client in C++
The client code looks very similar to the server. Here it is in full:
#include <Ice/Ice.h> #include <Printer.h> #include <stdexcept> using namespace std; using namespace Demo; int main(int argc, char* argv[]) { try { Ice::CommunicatorHolder ich(argc, argv); auto base = ich->stringToProxy("SimplePrinter:default -p 10000"); auto printer = Ice::checkedCast<PrinterPrx>(base); if(!printer) { throw std::runtime_error("Invalid proxy"); } printer->printString("Hello World!"); } catch(const std::exception& e) { cerr << e.what() << endl; return 1; } return 0; }
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/catch blocks to deal with errors.
The client code does the following:
- As for the server, we initialize the Ice run time by creating an
Ice::CommunicatorHolder
object, which creates and holds anIce::Communicator.
- 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.) - The proxy returned by
stringToProxy
is of typeIce::ObjectPrx
, which is at the root of the inheritance tree for interfaces. But to actually talk to our printer, we need a proxy for aPrinter
interface, not anObject
interface. To do this, we need to do a down-cast by callingcheckedCast<PrinterPrx>
. A checked cast sends a message to the server, effectively asking "is this a proxy for aPrinter
interface?" If so, the call returns a proxy to aPrinter
; otherwise, if the proxy denotes an interface of some other type, the call returns a null proxy. - We test that the down-cast succeeded and, if not, throw a
runtime_error
that terminates the client. - 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++ -I. -DICE_CPP11_MAPPING -c Printer.cpp Client.cpp c++ -o client Printer.o Client.o -lIce++11
Running Client and Server in 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:471: Ice::ConnectFailedException: connect failed: Connection refused