---
title: "Writing a Greeter Server"
url: https://docs.zeroc.com/ice/3.8/greeter-example/writing-a-greeter-server
language: cpp
docs_index: https://docs.zeroc.com/llms.txt
---

> For an index of every page, see [llms.txt](https://docs.zeroc.com/llms.txt).

# Writing a Greeter Server

Programming language: C++. Other languages: [C#](https://docs.zeroc.com/ice/3.8/greeter-example/writing-a-greeter-server/csharp.md), [Java](https://docs.zeroc.com/ice/3.8/greeter-example/writing-a-greeter-server/java.md), [Python](https://docs.zeroc.com/ice/3.8/greeter-example/writing-a-greeter-server/python.md), [Swift](https://docs.zeroc.com/ice/3.8/greeter-example/writing-a-greeter-server/swift.md).

This page provides a step-by-step guide to writing the server-side of our C++ Greeter application.

The server consists of:

- a C++ class that implements the `Greeter` interface we defined earlier in Slice
- an Ice object adapter that accepts TCP connections from clients, and later routes requests received over these connections to our Greeter implementation

You can find the complete source code for this example in the [ice-demos repository](https://github.com/zeroc-ice/ice-demos/tree/3.8/cpp/Ice/greeter). The code below is lightly simplified: it leaves out the demo’s error-reporting helper and the include guard in `Chatbot.h`.

## Compile Slice File with Slice Compiler

The first step when writing a C++ application with Ice is to compile the Slice definitions for this application with the Slice to C++ compiler (`slice2cpp`).

Here, we compile the `Greeter.ice` Slice file we wrote earlier:

```shell
slice2cpp Greeter.ice
```

This produces two files: a header file, `Greeter.h`, and a C++ source file, `Greeter.cpp`. The header file provides the `Greeter` abstract base class we implement in the code below, and `Greeter.cpp` is compiled into the server like any other source file. See [Using the Slice Compiler](https://docs.zeroc.com/ice/3.8/slice/using-the-slice-compiler/cpp.md) for the options `slice2cpp` accepts.

The C++ demo programs build with [CMake](https://cmake.org/): the `slice2cpp_generate` function of the Ice CMake package compiles `Greeter.ice` as part of the build. See [Using Ice with CMake](https://docs.zeroc.com/ice/3.8/build-tools/cmake.md).

## Implement the Servant Class

We implement the `Greeter` abstract base class with a C++ class, `Chatbot`. We call this implementation a servant class, or servant for short. `Chatbot` is declared in `Chatbot.h`:

```cpp
#include "Greeter.h"

namespace Server
{
    /// Chatbot is an Ice servant that implements Slice interface Greeter.
    class Chatbot : public VisitorCenter::Greeter
    {
    public:
        // Implements the pure virtual function in the base class
        // (VisitorCenter::Greeter) generated by the Slice compiler.
        std::string greet(std::string name, const Ice::Current&) override;
    };
}
```

Since the `Greeter` Slice interface only has one operation (`greet`), there is only one function that `Chatbot` needs to implement.

Notice that this function takes one more parameter than the Slice operation: a trailing `const Ice::Current&`. The Slice compiler adds this parameter to every operation it maps onto a servant. It describes the request being dispatched — the identity of the target Ice object, the operation name, the request context, and more. Our implementation doesn’t need any of this information, so we leave the parameter unnamed. See [operations](https://docs.zeroc.com/ice/3.8/slice/operations/cpp.md) for the full mapping.

> **Note**
>
> It is normal for servants like `Chatbot` to contain fields and other functions in addition to the needed ones from the generated base class. Due to our application’s simplicity, we don’t here though.

Next, let’s look at `Chatbot.cpp`, which provides the concrete implementation.

It starts out with some boilerplate `#include` statements and a `using namespace std`:

```cpp
#include "Chatbot.h"

#include <iostream>
#include <sstream>

using namespace std;
```

What really matters in this file is the implementation of `Chatbot::greet`.

```cpp
string
Server::Chatbot::greet(string name, const Ice::Current&)
{
    cout << "Dispatching greet request { name = '" << name << "' }" << endl;

    ostringstream os;
    os << "Hello, " << name << "!";
    return os.str();
}
```

You can see it takes a `name` parameter, and returns a greeting based on the provided `name`, matching both our header file, and indirectly, what was specified in our Slice file.

## Main Server Program

Our main server code is placed in its own file, `Server.cpp`, to keep it separate from the servant implementation. We start this file by including the following:

- `Chatbot.h`: This is the header we just wrote for our `Greeter` servant.
- `Ice/Ice.h`: This header provides definitions that are necessary for accessing the Ice runtime.
- `iostream`: So the server can access `cout` to print to the console.

We also add a `using` declaration for the `std` namespace to reduce clutter:

```cpp
#include "Chatbot.h"

#include <Ice/Ice.h>
#include <iostream>

using namespace std;
```

Next, we define the `main` function which runs the server.

We start by creating a [CtrlCHandler](https://code.zeroc.com/ice/3.8/api/cpp/classIce_1_1CtrlCHandler.html) object. It must come before anything else, and we come back to what it does in step 4:

```cpp
int
main(int argc, char* argv[])
{
    // CtrlCHandler is a helper class that handles Ctrl+C and similar signals.
    // It must be constructed at the beginning of the program,
    // before creating an Ice communicator or starting any thread.
    Ice::CtrlCHandler ctrlCHandler;

    // ...
```

Putting this aside, the interesting parts of this application can be broken down into four parts:

### 1. Create a Communicator

First, we create a [Communicator](https://docs.zeroc.com/ice/3.8/runtime/communicator/cpp.md) with `Ice::initialize`:

```cpp
Ice::CommunicatorPtr communicator = Ice::initialize(argc, argv);
```

The communicator is our main entry point into the Ice runtime. In this simple server application, we need this communicator to create an object adapter and nothing else (see next step).

We immediately place this communicator in a [CommunicatorHolder](https://code.zeroc.com/ice/3.8/api/cpp/classIce_1_1CommunicatorHolder.html). This stack-allocated helper calls `destroy` on the communicator in its destructor. Always call `destroy` on a communicator when you’re done with it, either explicitly or through a helper class. `destroy` closes connections gracefully and performs other cleanups.

```cpp
Ice::CommunicatorHolder communicatorHolder{communicator};
```

### 2. Create an Object Adapter

Next, we create an object adapter using our communicator:

```cpp
auto adapter = communicator->createObjectAdapterWithEndpoints("GreeterAdapter", "tcp -p 4061");
```

An object adapter serves two purposes in Ice:

- it accepts connections from clients
- it receives requests over these connections and routes them to servants based on the object identities carried by these requests

In this example, we create an object adapter named `GreeterAdapter` which listens for TCP connections on port 4061, and later receives requests over these connections.

We then register our `Chatbot` servant with this adapter under the identity `greeter`:

```cpp
// Register the Chatbot servant with the adapter.
adapter->add(make_shared<Server::Chatbot>(), Ice::Identity{"greeter"});
```

Later on, when the object adapter receives a request with identity `greeter`, it will route this request to our `Chatbot` servant. It is therefore essential that the client uses the same identity in its proxy.

### 3. Activate the Object Adapter

At this point, our object adapter does not accept connections yet. The endpoint is already bound, so the operating system completes the TCP handshake, but Ice never finishes establishing the connection — a client attempting to connect just waits, until it gives up with a `ConnectTimeoutException`.

We call `activate` to start accepting connections:

```cpp
adapter->activate();
cout << "Listening on port 4061..." << endl;
```

Our server is now active, waiting for connections and requests from clients, and dispatching requests for `greeter` to our `Chatbot` servant.

### 4. Keep Running Until Ctrl+C

It is essential to keep the server running, and not let `main` return prematurely. We use the following technique to achieve this goal:

- wait in the main thread until an event occurs
- catch Ctrl+C signals in a background thread and trigger this event upon Ctrl+C

The event we chose is “the communicator was shut down”. But you could pick any other event; for example, you could implement the same logic with a `std::promise`.

The Ctrl+C handling is courtesy of the `CtrlCHandler` object we created earlier. We call its `setCallback` function to specify what to do when it catches a signal. In this case, we want to shut down the communicator:

```cpp
// Shut down the communicator when the user presses Ctrl+C.
ctrlCHandler.setCallback(
    [communicator](int signal)
    {
        cout << "Caught signal " << signal << ", shutting down..." << endl;
        communicator->shutdown();
    });
```

Next, we block the main thread until the communicator is shut down:

```cpp
communicator->waitForShutdown();
```

Finally, once the communicator is shut down, we reach the end of `main` and return:

```cpp
return 0;
```

At this point, the destructor of the `CommunicatorHolder` destroys the communicator and indirectly our object adapter, all incoming connections are closed, and various other cleanups take place.

## Running the Server

After building the server (see the demo’s [README](https://github.com/zeroc-ice/ice-demos/blob/3.8/cpp/Ice/greeter/README.md) for instructions), running it is as simple as running any other executable:

**Linux and macOS:**

```shell
./build/server
```

**Windows:**

```shell
build\server
```

The server prints its listening message, then waits for clients:

```text
Listening on port 4061...
```

Leave it running and start the [Greeter client](https://docs.zeroc.com/ice/3.8/greeter-example/writing-a-greeter-client/cpp.md) in a separate terminal. Each request the client sends shows up in the server’s output:

```text
Dispatching greet request { name = 'alice' }
Dispatching greet request { name = 'bob' }
Dispatching greet request { name = 'carol' }
```

Press Ctrl+C to stop the server.

You can optionally set Ice properties on the command line. This works because `Ice::initialize` parses the arguments we handed it: it applies every `--Ice.*` option it recognizes as a configuration property, and removes it from `argv`. For example, this command sets `Ice.Trace.Dispatch` to `1` and `Ice.Trace.Network` to `2`:

```shell
./build/server --Ice.Trace.Dispatch=1 --Ice.Trace.Network=2
```
