Simple Hello World RPC

We will now define a simple RPC handler that prints “Hello World”.

Server

Let’s take again the server code from the previous section and improve it.

#include <iostream>
#include <thallium.hpp>

namespace tl = thallium;

void hello(const tl::request& req) {
    std::cout << "Hello World!" << std::endl;
}

int main(int argc, char** argv) {

    tl::engine myEngine("tcp", THALLIUM_SERVER_MODE);
    myEngine.define("hello", hello).disable_response();
    std::cout << "Server running at address " << myEngine.self() << std::endl;

    return 0;
}

The engine::define method is used to define an RPC. The first argument is the name of the RPC (a string), the second is a function. This function should take a const reference to a thallium::request as argument. We will see in a future example what this request object is used for. The disable_response() method is called to indicate that the RPC is not going to send any response back to the client.

Client

Let’s now take a look at the client code.

#include <thallium.hpp>

namespace tl = thallium;

int main(int argc, char** argv) {

    if(argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <address>" << std::endl;
        exit(0);
    }

    tl::engine myEngine("tcp", THALLIUM_CLIENT_MODE);
    tl::remote_procedure hello = myEngine.define("hello").disable_response();
    tl::endpoint server = myEngine.lookup(argv[1]);
    hello.on(server)();

    return 0;
}

The client does not declare the hello function, since its code is on the server. Instead, it calls engine::define with only the name of the RPC, indicating that there exists on the server a RPC that goes by this name. Again we call disable_response() to indicate that this RPC does not send a response back. We then use the engine to perform an address lookup. This call returns an endpoint representing the server.

Finally we can call the hello RPC by associating it with an endpoint. hello.on(server) actually returns an instance of a class callable_remote_procedure which has its parenthesis operator overloaded to make it usable like a function.