use std::sync::mpsc::{channel, Sender}; use std::thread; use std::time::Duration; use serde_json::Value; use zbus::message::{Message, Request}; use zbus::rpc::IOHandlers; use zbus::wsocket::Instruct; /// rpc 例子初步实现 fn main() { let (tx, rx) = channel::<(Request, Sender)>(); let mut io_handler = IOHandlers::new(25); io_handler.add_method("test0".into(), |mut params: Value| { Ok(if params.is_array() {// TODO 这块的代码都可以用宏来消防模版代码 let params = params.as_array_mut().unwrap(); params.reverse(); let a = params.pop().unwrap(); let b = params.pop().unwrap(); let a = serde_json::from_value(a).unwrap(); let b = serde_json::from_value(b).unwrap(); let result = add(a, b); println!("{}+{}={}", a, b, result); Value::from(result) } else { Value::Null }) }); io_handler.add_method("test1".into(), |mut params: Value| { Ok(if params.is_array() {// TODO 这块的代码都可以用宏来消防模版代码 let params = params.as_array_mut().unwrap(); params.reverse(); let a = params.pop().unwrap(); let b = params.pop().unwrap(); let c = params.pop().unwrap(); let a = serde_json::from_value(a).unwrap(); let b = serde_json::from_value(b).unwrap(); let c = serde_json::from_value(c).unwrap(); let result = add_three(a, b, c); Value::from(result) } else { Value::Null }) }); thread::spawn(move || { loop { if let Ok((req, sender)) = rx.recv() { io_handler.handler_request(req, sender); } } }); let (sender, receiv) = channel::(); for i in 0..1000 { let method = format!("test{}", (i % 2)); println!("request is {}", method); let a = 1 + i; let b = 2 + i; let c = 3 + i; let params = vec![Value::from(a), Value::from(b), Value::String(format!("{}", c))]; let req = Request::builder().url(method).body(Value::Array(params)).id("4145877412").build(); tx.send((req, sender.clone())); } thread::sleep(Duration::from_secs(2)); for i in 0..1000 { receiv.recv().map(|res| match res { Instruct::Delivery(msg, _) => { if let Message::Response(resp) = msg { println!("result is {}", resp.body().as_i64().unwrap()); }; } _ => {} }); } } pub fn add(a: i32, b: i32) -> i32 { a + b } pub fn add_three(a: i32, b: i32, c: String) -> i32 { println!("c is {}", c); a + b }