jharmer95 / rpc.hpp

A simple header-only library for supporting remote procedure calls using a variety of extensible features
BSD 3-Clause "New" or "Revised" License
4 stars 2 forks source link
cpp header-only hpp json remote-execution remote-procedure-calls rpc serialization

cmake codecov

rpc.hpp

A simple header-only library for supporting remote procedure calls using a variety of extensible features.

License

rpc.hpp is licensed under the BSD 3-Clause License.

Features

Known Limitations

Documentation

See Doxygen docs here.

Basic Example

For more examples see examples.

server.cpp

#define RPC_HPP_SERVER_IMPL

#include <rpc_adapters/rpc_njson.hpp>

#include <string>

using rpc_hpp::adapters::njson;
using rpc_hpp::adapters::njson_adapter;

int Add(int n1, int n2)
{
    return n1 + n2;
}

void AppendStr(std::string& str, const char* append)
{
    str.append(append);
}

class RpcServer : public rpc_hpp::server_interface<njson_adapter>
{
public:
    RpcServer(const char* address)
    {
        // initialize server...
    }

    // ...

    void Run()
    {
        std::string data;

        // Get data from client...

        // Sink data into the dispatch function to get result data
        auto result_data = dispatch(std::move(data));

        // Send result data back to client...
    }
};

int main()
{
    RpcServer my_server{"address"};
    my_server.bind("Add", &Add);
    my_server.bind("AppendStr",
        [](std::string& str, const std::string& append) {
            AppendStr(str, append.c_str());
        }
    );

    while (true)
    {
        my_server.Run();
    }
}

client.cpp

#define RPC_HPP_CLIENT_IMPL

#include <rpc_adapters/rpc_njson.hpp>

#include <cassert>
#include <string>

using rpc_hpp::adapters::njson_adapter;

class RpcClient : public rpc_hpp::client_interface<njson_adapter>
{
public:
    RpcClient(const char* address)
    {
        // initialize client...
    }

    // ...

private:
    void send(const std::string& mesg) override
    {
        // Send mesg to server...
    }

    void send(std::string&& mesg) override
    {
        // Send mesg to server...
    }

    std::string receive() override
    {
        // Get message back from server...
    }
};

int main()
{
    RpcClient my_client{ "address" };

    const auto result = my_client.template call_func<int>("Sum", 1, 2);
    assert(result == 3);

    std::string str{ "Hello" };
    my_client.call_func("AppendStr", str, " world!");
    assert(str == "Hello world!");
}