Remote Spawning of Actors

Remote spawning is an extension of the dynamic spawn using run-time type names (see Adding Custom Actor Types experimental). The following example assumes a typed actor handle named calculator with an actor implementing this messaging interface named “calculator”.

void client(actor_system& sys, const config& cfg) {
  auto host = get_or(cfg, "host", default_host);
  auto port = get_or(cfg, "port", default_port);
  auto node = sys.middleman().connect(host, port);
  if (!node) {
    sys.println("*** connect failed: {}", node.error());
    return;
  }
  auto type = "calculator";             // type of the actor we wish to spawn
  auto args = make_message();           // arguments to construct the actor
  auto tout = std::chrono::seconds(30); // wait no longer than 30s
  auto worker = sys.middleman().remote_spawn<calculator>(*node, type, args,
                                                         tout);
  if (!worker) {
    sys.println("*** remote spawn failed: {}", worker.error());
    return;
  }
  // start using worker in main loop
  client_repl(sys, *worker);
  // be a good citizen and terminate remotely spawned actor before exiting
  anon_send_exit(*worker, exit_reason::kill);
}

We first connect to a CAF node with middleman().connect(...). On success, connect returns the node ID we need for remote_spawn. This requires the server to open a port with middleman().open(...) or middleman().publish(...). Alternatively, we can obtain the node ID from an already existing remote actor handle—returned from remote_actor for example—via hdl->node(). After connecting to the server, we can use middleman().remote_spawn<...>(...) to create actors remotely.