Skip to content

Instantly share code, notes, and snippets.

@jrraymond
Created August 18, 2018 13:36
Show Gist options
  • Save jrraymond/1a7ab59c165c9daf8a077d51686c4eaf to your computer and use it in GitHub Desktop.
Save jrraymond/1a7ab59c165c9daf8a077d51686c4eaf to your computer and use it in GitHub Desktop.
tarpc closure in server
/*
nightly-x86_64-unknown-linux-gnu
[dependencies]
serde = "^1.0"
tarpc = "0.12.0"
tarpc-plugins = "0.4.0"
*/
#![feature(plugin, use_extern_macros, proc_macro_path_invoc)]
#![plugin(tarpc_plugins)]
#[macro_use]
extern crate tarpc;
use std::sync::mpsc;
use std::thread;
use tarpc::sync::{client, server};
use tarpc::sync::client::ClientExt;
use tarpc::util::Never;
use std::clone::Clone;
use std::marker::Send;
service! {
rpc hello(name: String) -> String;
}
type TaskFn = Fn();
#[derive(Clone)]
struct HelloServer<F> {
task: F,
}
impl<F> SyncService for HelloServer<F>
where F: Send + Clone + 'static + Fn() {
fn hello(&self, name: String) -> Result<String, Never> {
(self.task)();
Ok(format!(
"Hello from thread {}, {}!",
thread::current().name().unwrap(),
name
))
}
}
fn main() {
let task = || { println!("Doing work"); };
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let handle = HelloServer { task }
.listen("localhost:0", server::Options::default())
.unwrap();
tx.send(handle.addr()).unwrap();
handle.run();
});
let client = SyncClient::connect(rx.recv().unwrap(), client::Options::default()).unwrap();
println!("{}", client.hello("Mom".to_string()).unwrap());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment