diff options
author | hozan23 <hozan23@karyontech.net> | 2024-05-19 22:20:03 +0200 |
---|---|---|
committer | hozan23 <hozan23@karyontech.net> | 2024-05-19 22:20:03 +0200 |
commit | a6016c7eeb11fc8aeaa1a3b160b970b15362695d (patch) | |
tree | a872c02076836811257b59ce7d88f9ef5a85f5ed /jsonrpc/examples/tokio_server/src | |
parent | 1c520b20f70ddbdab885ec6c4bf5c87893a26eb4 (diff) |
add tokio examples to p2p, jsonrpc, and net crates
Diffstat (limited to 'jsonrpc/examples/tokio_server/src')
-rw-r--r-- | jsonrpc/examples/tokio_server/src/main.rs | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/jsonrpc/examples/tokio_server/src/main.rs b/jsonrpc/examples/tokio_server/src/main.rs new file mode 100644 index 0000000..978c90a --- /dev/null +++ b/jsonrpc/examples/tokio_server/src/main.rs @@ -0,0 +1,58 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use karyon_jsonrpc::{rpc_impl, Error, Server}; + +struct Calc { + version: String, +} + +#[derive(Deserialize, Serialize)] +struct Req { + x: u32, + y: u32, +} + +#[derive(Deserialize, Serialize)] +struct Pong {} + +#[rpc_impl] +impl Calc { + async fn ping(&self, _params: Value) -> Result<Value, Error> { + Ok(serde_json::json!(Pong {})) + } + + async fn add(&self, params: Value) -> Result<Value, Error> { + let params: Req = serde_json::from_value(params)?; + Ok(serde_json::json!(params.x + params.y)) + } + + async fn sub(&self, params: Value) -> Result<Value, Error> { + let params: Req = serde_json::from_value(params)?; + Ok(serde_json::json!(params.x - params.y)) + } + + async fn version(&self, _params: Value) -> Result<Value, Error> { + Ok(serde_json::json!(self.version)) + } +} + +#[tokio::main] +async fn main() { + env_logger::init(); + // Register the Calc service + let calc = Calc { + version: String::from("0.1"), + }; + + // Creates a new server + let server = Server::builder("tcp://127.0.0.1:6000") + .expect("Create a new server builder") + .service(calc) + .build() + .await + .expect("start a new server"); + + // Start the server + server.start().await.unwrap(); +} |