A simple header-only library for supporting remote procedure calls using a variety of extensible features.
rpc.hpp
is licensed under the BSD 3-Clause License.
constexpr if
.librpc
and gRPC
.std::string
/ std::vector
supported out of the box (more STL containers to come).template
methods for serializing types outside of their controlconst char*
/ const char[]
for strings) cannot be
passed across an RPC boundary.call_header_func()
).See Doxygen docs here.
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!");
}