This example demonstrates an in-process communication using tarpc::transport::channel::unbounded(). In production, you would typically use network transports like serde_transport with the tcp feature enabled.
To run this example, ensure your Cargo.toml includes:
anyhow = "1.0"
futures = "0.3"
tarpc = { version = "0.37", features = ["tokio1"] }
tokio = { version = "1.0", features = ["rt-multi-thread", "macros"] }
use futures::prelude::*;
use tarpc::client;
use tarpc::context;
use tarpc::server::{self, Channel};
#[tarpc::service]
trait World {
async fn hello(name: String) -> String;
}
#[derive(Clone)]
struct HelloServer;
impl World for HelloServer {
async fn hello(self, _: context::Context, name: String) -> String {
format!("Hello, {name}!")
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let (client_transport, server_transport) = tarpc::transport::channel::unbounded();
let server = server::BaseChannel::with_defaults(server_transport);
tokio::spawn(
server.execute(HelloServer.serve())
.for_each(|response| async move {
tokio::spawn(response);
})
);
let mut client = WorldClient::new(client::Config::default(), client_transport).spawn();
let hello = client.hello(context::current(), "Stim".to_string()).await?;
println!("{hello}");
Ok(())
}